Add a note about Python functools.singledispatch decorator

This commit is contained in:
2022-06-07 07:58:11 +02:00
parent 4e9442c835
commit ab9ee4660a
2 changed files with 75 additions and 1 deletions

View File

@@ -1,6 +1,6 @@
:PROPERTIES: :PROPERTIES:
:ID: 4fabfe6a-b104-464f-8a87-dfd7d761dbcc :ID: 4fabfe6a-b104-464f-8a87-dfd7d761dbcc
:mtime: 20220601215830 :mtime: 20220607075713
:ctime: 20211230101535 :ctime: 20211230101535
:END: :END:
#+title: Python #+title: Python
@@ -27,6 +27,8 @@ La méthode ~__repr__~ est utilisée pour le debug quand ~__str__~ pour l'utilis
** Fonctions Built-in ** Fonctions Built-in
*** [[id:487f57f5-e9fc-4df7-ae14-b41f9c1fa186][Fonction vars]] *** [[id:487f57f5-e9fc-4df7-ae14-b41f9c1fa186][Fonction vars]]
*** [[id:acda43fa-70be-4939-9128-47114e48e4cb][Fonction zip]] *** [[id:acda43fa-70be-4939-9128-47114e48e4cb][Fonction zip]]
** Functools module
*** [[id:25d994fd-375b-429d-af38-6afba818159f][functools.singledispatch]]
* Frameworks * Frameworks
** Web ** Web

View File

@@ -0,0 +1,72 @@
:PROPERTIES:
:ID: 25d994fd-375b-429d-af38-6afba818159f
:mtime: 20220607075600
:ctime: 20220607074003
:END:
#+title: functools.singledispatch
* Introduction
Le module /functools/ permet la définition de /single dispatch methods/ :
* Une sorte de méthode générique pour laquelle différentes implémentations sont écrites,
* L'implémentation à exécuter est déterminée d'après le type du premier argument non /self/ ou non /cls/,
* Peut être imbriqué (/nested/) avec d'autres décorateurs mais /singledispatchmethod/ doit être le plus englobant (cf. howto),
* Depuis Python3.8 (3.9 pour les imbrications, cf. PCR 83860 en référence).
* Howto
** Usage de base
#+BEGIN_SRC python :results output
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
def neg(self, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(self, arg: int):
return -arg
@neg.register
def _(self, arg: bool):
return not arg
negator = Negator()
print(f'{negator.neg(5) = }')
print(f'{negator.neg(False) = }')
#+END_SRC
#+RESULTS:
: negator.neg(5) = -5
: negator.neg(False) = True
** Imbrication (/nested/) avec d'autres /decorator/
#+BEGIN_SRC python :results output
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
@classmethod
def neg(cls, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
@classmethod
def _(cls, arg: int):
return -arg
@neg.register
@classmethod
def _(cls, arg: bool):
return not arg
print(f'{Negator.neg(5) = }')
print(f'{Negator.neg(False) = }')
#+END_SRC
#+RESULTS:
* Références
* [[https://medium.com/@sunilrana123/python-trick-functools-singledispatch-4cdf71843cd2][Python Trick : functools.singledispatch - Medium]]
* [[https://docs.python.org/3/library/functools.html#functools.singledispatchmethod][functools.singledispatch - Python]]
* [[https://github.com/python/cpython/issues/83860][functools: singledispatchmethod doesn't work with classmethod #83860 - CPython Github]]