Mastering Python Refactoring: Simplifying Code with the Dictionary Dispatch Pattern

preview_player
Показать описание
In today's video we look at how to refactor an if-elif-elif...-else statement using the "dictionary dispatch pattern" in Python. 💡

As a bonus we also add some ad hoc testing to the mix and refactor further using the operator module. 😎

---

And last but not least, we appreciate any feedback to make our YouTube content better 💡
Рекомендации по теме
Комментарии
Автор

the beauty of python is that, it is a new concept to me, but if i read the code, i know what it does.

sckhoo
Автор

the video is amazing, this kind of "refactor" video would be much helpful for python devs who wants to improve their coding skills :) very practical, thanks

Pulenbach
Автор

Thanks a lot for the video! Actually my favorite pattern with Python, thanks to the fact that functions are first class objects. What do you think about the idea of providing the respective operation functions with a self-registering decorator and thus automatically adding them to the OPERATIONS-dictionary. I like the idea, or maybe not explicit enough?

def auto_register(func):
"""Automatically store an operation function in operations dict"""
OPERATIONS[func.__name__] = func
return func

mirat
Автор

Great video, thanks! One of my favorite tricks in all Python programming.
Wanted to ask: did you consider structural pattern matching as full replacement for this technique? Maybe you see some limitations in it?

illiakhoroshykh
Автор

in python functions are first class citizens
you can also do this
```
from enum import Enum
from typing import Callable, Union

Num = Union[int, float]
Fn = Callable[[Num], Num]

class Op(Enum):
def add(a: Num, b: Num) -> Num:
return a + b

def sub(a: Num, b: Num) -> Num:
return a - b

def perform(op: Fn, a: Num, b: Num) -> Num:
return op(a, b)

def main():
a = 1
b = 2
print(perform(Op.add, a, b)) # 3
print(perform(Op.sub, a, b)) # -1
print(perform(Op.mul, a, b)) # !crash - not sure if this should be handled or not

main()
```

michalbotor
Автор

Is there an efficiency gain between what is shown in the video and using the more recent Python Structural Pattern matching to do the dispatching? PEP 636 for reference.

ciaran
Автор

Even better: just access the dict and catch the KeyError exception.

matteodelgrosso