Skip to main content
 首页 » 编程设计

python之字符串是否可以作为 Callable 类型中的 int 接受

2024年10月24日25bhlsheji

我想知道我是否误解了Callable的用法。

def func(f1:int, f2:int, s:str) -> bool: 
    return isinstance(f2, int) 
 
def func2(fn:Callable[[int, int, str], bool]): 
    print(fn(42.42, '42.42', 'hello mum'))  # Incorrectly passed? 
 
func2(func) 

我希望我的 PyCharm IDE 将打印语句行标记为类型失败,因为它提供了 (float, str, str) 而不是所需的 (int, int, str)。它没。 但是,在以下代码中,func2(func) 的 func 被标记为类型错误。

def func(f1:int, f2:str, s:str) -> bool: 
    return isinstance(f2, int) 
 
def func2(fn:Callable[[int, int, str], bool]): 
    print(fn(42, 42, 'hello mum')) 
 
func2(func)  # Correctly flagged as a type error 

请您参考如下方法:

这似乎是 PyCharm 的错误或功能缺失。如果你使用 mypy ,你正确地得到了预期的类型错误:

test.py: note: In function "func2": 
test.py:7: error: Argument 1 has incompatible type "float"; expected "int" 
test.py:7: error: Argument 2 has incompatible type "str"; expected "int"