我有以下代码作为最低限度可重现的示例:
from typing import Any, Callable, Generic, Optional, TypeVar, Union
from random import choice
T1 = TypeVar("T1")
class qux(Generic[T1]):
def foo(self) -> Callable[[T1], None]:
def foo_wrapper(arg:T1):
print(f'Bar wrapper called with argument {arg}')
return foo_wrapper
def bar(self) -> Callable[[], None]:
def bar_wrapper():
print('Foo wrapper called without arguments')
return bar_wrapper
def buzz(self, func:Union[Callable[[T1], Any], Callable[[], Any]], arg: Optional[T1] = None):
if arg:
func(arg)
else:
func()
def choice_impl(self, flag:bool):
if flag:
return self.foo()
else:
return self.bar()
qux_instance = qux()
value = None
if choice((True, False)):
value = 42
flag = value is not None
implementation = qux_instance.choice_impl(flag=flag)
if flag:
qux_instance.buzz(func=implementation, arg=value)
else:
qux_instance.buzz(func=implementation)
皮兰斯在第 21 行发誓:
Expected 0 positional arguments (parameter) arg: T1@qux
和23:
Expected 1 more positional argument (parameter) func: ((T1@qux) -> Any) | (() -> Any)
因为它不知道func函数参数buzz在调用时将具有什么签名。虽然这段代码运行起来总是没有错误。我怎么解决这个问题?这是 Pylance 的错误还是与停止问题有关?还是我的手歪了?
cast在这种情况下,您可以从模块中使用typing:但这本质上禁用了保护,静态分析器将无法检查您是否传递了一个带有一个参数和一个参数的函数,或者一个没有参数且没有传递参数的函数。