Episodio 32: Python moderno 4 ... Click!
Muchas veces, dentro de una biblioteca hecha en Python hay un comando útil con ganas de salir. Para lograrlo: click!
Muchas veces, dentro de una biblioteca hecha en Python hay un comando útil con ganas de salir. Para lograrlo: click!
I am doing a series of videos (spanish only!) about "modern Python", showing the modern replacements for things that are ... dense in their original forms.
So, I showed Poetry as an alternative to writing your setup.py and Click as a way to do things easier than argparse, and Pathlib instead of os.path and then I wanted to show Enums. Which are not so new since they have been there since Python 3.4 but I feel they are not used widely enough.
And then I noticed that they help do a "safer" version of the classical Python version of C's switch / case where you can be sure of not leaving any values unhandled.
So, I wrote a little thing and pushed it to PyPI: https://pypi.org/project/enum-switch/
It's a tiny project, but here's an example of how you use it.
from enum import Enum from enum_switch import Switch class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 class MySwitch(Switch): def RED(self): return "Apple" def GREEN(self): return "Kiwi" def BLUE(self): return "Sky" switch = MySwitch(Color) print(switch(Color.RED)) Apple
If MySwitch was missing one of those "handlers" for the Enum values? That's an exception. If you don't want to define them all? Do a default() there.
I like this solution, but am very interested to know if someone has come up with a better one? Comments are enabled, feel free to tell me :-)
Pathlib es para crear / modificar / manipular paths. O, como decíamos antes os.path.join(crear, modificar, manipular paths) ... mas allá del chiste, es muuuuucho más legible. Veamos un ejemplo "real" de código que veo seguido y dejemos de usar os.path.
Pathlib: https://docs.python.org/3/library/pathlib.html
Herramientas para mejorar la calidad de tu código! Que más querés????
Primera parte de una serie mostrando herramientas nuevas que reemplazan cosas viejas con algo mejor. En este video: poetry, reemplazando setup.py!