I want to implement method overloading in Python. (I know by default Python does not support overloading. Thats what I am asking this question.)
I have following code structure:
def parse():
results = doSomething()
return results
x = namedtuple('x',"a b c")
def parse(query: str, data: list[x]):
results = doSomethingElse(query, data)
return results
The only solution I can think of is do a check for arguments
def parse(query: str, data: list[x]):
if query is None and data is None:
results = doSomething()
return results
else:
results = doSomethingElse(query, data)
return results
Is it possible to do method overloading in Python like in Java?
i.e. with out the branching? Is there is a clear way using decorator or some library?
Please help.
CodePudding user response:
There is the typing.overload
decorator used for properly annotating a callable with two or more distinct call signatures. But it still requires exactly one actual implementation. The usage would be as follows:
from typing import overload
@overload
def parse(query: None = None, data: None = None) -> None:
...
@overload
def parse(query: str, data: list[object]) -> None:
...
def parse(query: str | None = None, data: list[object] | None = None) -> None:
if query is None and data is None:
print("something")
else:
print(f"something else with {query=} and {data=}")
parse() # something
parse("foo", [1]) # something else with query='foo' and data=[1]
Note that the ellipses ...
are meant literally, i.e. that is all that should be in the "body" of that function overload.
That is how it is done in Python. As mentioned in the comments already, there is no syntax for literally writing overloaded function implementations. If you write two implementations, the last one will simply override the first.
Even if you could build something like that with syntactically pleasing decorators, I would probably advise against it because it will likely confuse everyone else since it is not how Python was designed. Also, if you have a lot of complex overloads that all require different implementation logic, I would argue this is probably just bad design. And if the branches are clear/simple as in your example, then I see no problem with having them in one function body.
CodePudding user response:
You can use multipledispatch decorator.