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

标签 python typing

我想知道我是否误解了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 将 print 语句行标记为类型失败,因为它提供了 (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"

关于python - Callable 类型中的字符串是否可以作为 int 接受?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34253843/

相关文章:

python - 有没有办法以可变的次数找到第 0 个索引?

python - 以静态类型语言实现干净且类型安全的状态机?

python - 我可以确定函数会因键入而引发哪些错误?

Typescript `in` 运算符类型保护仅作为文字缩小

java - hibernate保存中的可序列化字符串(对象实体,可序列化id)

python - 如何直接从 Flask render_template 使用 Jinja2 扩展

python - 如何在 Python 中搜索正则表达式匹配项?

python - 使用 .replace 替换连续的单引号和双引号?

python - 保留 DataFrame 中列的第一个元素

macos - PhpStorm - 输入越南语时出错