打字模块中的重载装饰器似乎不像预期的那样

打字模块中的重载装饰器似乎不像预期的那样

本文介绍了打字模块中的重载装饰器似乎不像预期的那样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>>从键入导入重载>>>@超载... def hello(s: int):...返回得到一个整数!">>>def hello(s: str):...返回得到一个字符串"

为什么调用 hello(1) 调用带有字符串参数的函数?理想情况下,@overload 操作符应该处理它,对吗?

解决方案

不幸的是,python 不允许函数重载.每次你认为你正在重载函数时,你只是覆盖了之前的函数声明.引用自

mypy 也抱怨无效类型:

➜ mypy test.pytest.py:25: 错误:+ 不支持的操作数类型(int"和str")

typing 模块的目的是允许第三方工具对您的代码进行静态检查.这里没有魔法——所有类型在运行时都会被忽略.

>>> from typing import overload

>>> @overload
... def hello(s: int):
...     return "Got an integer!"

>>> def hello(s: str):
...     return "Got a string"

Why does the calling hello(1) call the function with the string argument? Ideally, the @overload operator should handle it, right?

解决方案

Unfortunately, python does not allow function overloading. Each time you think you are overloading function, you are just overwriting previous function declaration. Quote from the docs:

The correct usage of typing.overload is as follows:

from typing import overload


@overload
def hello(s: int) -> str:
    ...


@overload
def hello(s: str) -> str:
    ...


def hello(s):
    if isinstance(s, int):
        return "Got an integer!"
    if isinstance(s, str):
        return "Got a string"
    raise ValueError('You must pass either int or str')


if __name__ == '__main__':
    print(hello(1))

To show the actual benefit of typing.overload lets change def hello(s: int) to return int instead of str:

from typing import overload


@overload
def hello(s: int) -> int:
    ...


@overload
def hello(s: str) -> str:
    ...


def hello(s):
    if isinstance(s, int):
        return "Got an integer!"
    if isinstance(s, str):
        return "Got a string"
    raise ValueError('You must pass either int or str')


if __name__ == '__main__':
    print(hello(1))
    a = hello(1) + 1
    b = hello(1) + 'a'

Note, that the actual implementation still returns str - python does not perform any checks here. However, PyCharm raises a warning:

mypy also complains about invalid types:

➜ mypy test.py
test.py:25: error: Unsupported operand types for + ("int" and "str")

The purpose of typing module is to allow third party tools to perform static checking of your code. There is no magic here - all types are ignored at runtime.

这篇关于打字模块中的重载装饰器似乎不像预期的那样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:24