如何在Python中进行函数重载?

hts6caw3  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(131)

I want to implement function overloading in Python. I know by default Python does not support overloading. That is what I am asking this question.
I have the following code:

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 to check the 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 function overloading in Python like in Java (i.e. with out the branching)?
Is there is a clear way using a decorator or some library?

wvt8vs2t

wvt8vs2t1#

有一个typing.overload装饰器可以用来正确地注解一个具有两个或更多不同调用签名的可调用对象。但是它仍然需要一个实际的实现。用法如下:

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]

请注意,省略号...是字面上的意思,也就是说,这是该函数重载的“主体”中应该包含的全部内容。
这就是Python中的做法。正如在注解中提到的,没有语法可以用来编写重载函数的实现。如果你编写了两个实现,最后一个将简单地覆盖第一个。
即使你 * 可以 * 用语法上令人满意的装饰器构建类似的东西,我可能会建议不要这样做,因为这可能会让其他人感到困惑,因为这不是Python的设计方式。而且,如果你有很多复杂的重载,它们都需要不同的实现逻辑,我会说这 * 可能 * 只是糟糕的设计。如果分支像你的例子中那样清晰/简单,那么我认为将它们放在一个函数体中没有问题。

相关问题