Julia's burgeoning popularity has renewed my interest in dynamic dispatch.  
It seems to me that many methods that have been written as a giant switch 
on types can more clearly be written using dynamic dispatch.  It was 
prettty exciting to see that Python already has single dispatch built in, 
and that it supports type annotations!

Would it be possible and desirable to extend it slightly to support Union 
types?

---

In [1]: from functools import singledispatch

In [3]: from typing import Any, Union

In [4]: @singledispatch
   ...: def a(x: Any):
   ...:     print("a")
   ...: 

In [5]: class X: pass

In [6]: class Y: pass

In [7]: @a.register
   ...: def _(x: Union[X, Y]):
   ...:     print("b")
   ...: 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-b6a194bcade0> in <module>
      1 @a.register
----> 2 def _(x: Union[X, Y]):
      3     print("b")
      4 

~/.pyenv/versions/3.8.5/lib/python3.8/functools.py in register(cls, func)
    858             argname, cls = next(iter(get_type_hints(func).items()))
    859             if not isinstance(cls, type):
--> 860                 raise TypeError(
    861                     f"Invalid annotation for {argname!r}. "
    862                     f"{cls!r} is not a class."

TypeError: Invalid annotation for 'x'. typing.Union[__main__.X, __main__.Y] 
is not a class.

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HF5HDXQ2SXZHO3TWODIRQATTE4TCAWPL/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to