3 ms·
I don't miss it a lot in Python except for some cases such as: area(Circle circle): ... area(Square square): ... You could say "Ah! B
by cuchoi 7y ago
I don't miss it a lot in Python except for some cases such as:
area(Circle circle):
...
area(Square square):
...
You could say "Ah! But that could be something that you define in each class, like square.calculate_area()". Yes, but sometimes you don't have access to the class. You could monkey-patch it but that's not something that I like to do.
- mumblemumble 7y agoThe Pythonic way to deal with that would be to just remember that Python is a dynamic language: def area(shape): if isinstance(shape, Circle): ... if isinstance(shape, Square): ... Or, if you want better coverage from your type checker, from typing import overload @overload def area(shape: Circle): ... @overload def area(shape: Square): ... def area(shape): if isinstance(shape, Circle): ... if isinstance(shape, Square): ... This still isn't real overloading. The last one is the one and only function. All the other two bits do is tell the static type checker what kinds of arguments it's prepared to support. edit: Scratch that, I think what I'd really go for in a simpler case like this would just be def area(shape: Union[Circle, Square]): ...
- closed 7y agoPython including functools.singledispatch I think is a strong indicator that function overloading IS pythonic (or at least pythonic enough to core python developers)
- joshuamorton 7y agoI don't know that I've seen singledispatch used anywhere, and the standard library includes a lot of unpythonic code (and entire modules). As a simple example, the unittest module is entirely unpythonic. Singledispatch was mostly included to handle specific cases where singledispatch is very clearly useful (the PEP mentions pprint and copy), but not as a generic tool for common end-user code.
- deleted 7y ago[deleted]