3

我正在使用multimethod包(1.4)来重载方法。我需要有联合类型(或 TypeVar)作为输入类型;但是,这会导致问题。例子:

from typing import Union
from multimethod import multimethod


@multimethod
def func(x: int):
    print(x)

@multimethod
def func(x: int, y: int):
    print(x, y)

func(1)
func(2, 3)

这工作正常,并输出

1
2 3

正如预期的那样。但是,此代码崩溃:

from typing import Union
from multimethod import multimethod


@multimethod
def func(x: int):
    print(x)

@multimethod
def func(x: Union[int, float], y: int):
    print(x, y)

func(1)
func(2, 3)

输出:

1
Traceback (most recent call last):
  File "C:\Users\...\testing.py", line 14, in <module>
    func(2, 3)
  File "C:\Users\...\.conda\envs\...\lib\site-packages\multimethod\__init__.py", line 184, in __call__
    return self[tuple(map(self.get_type, args))](*args, **kwargs)
TypeError: func() takes 1 positional argument but 2 were given

有没有办法拥有联合类型不同数量的参数?谢谢!

4

0 回答 0