Python 2中的类型提示

xuo3flqw  于 2023-03-28  发布在  Python
关注(0)|答案(3)|浏览(178)

PEP 484中,类型提示被添加到Python 3中,并包含了typing模块。在Python 2中有什么方法可以做到这一点吗?我所能想到的是有一个装饰器添加到方法中来检查类型,但这会在运行时失败,并且不能像提示所允许的那样被及早捕获。

jvlzgdj9

jvlzgdj91#

根据PEP 484中定义类型提示的Python 2.7和跨代码的建议语法,有一种替代语法可以与Python 2.7兼容。但它不是强制性的,所以我不知道它的支持情况如何,但引用PEP:
一些工具可能希望在必须与Python 2.7兼容的代码中支持类型注解。为此,此PEP有一个建议的(但不是强制性的)扩展,其中函数注解放置在# type中:comment。这样的注解必须紧跟在函数头之后(在docstring之前)。例如:Python 3代码:

def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:
    """Embezzle funds from account using fake receipts."""
    <code goes here>

等效于以下内容:

def embezzle(self, account, funds=1000000, *fake_receipts):
    # type: (str, int, *str) -> None
    """Embezzle funds from account using fake receipts."""
    <code goes here>

有关mypy支持,请参阅Type checking Python 2 code

2izufjch

2izufjch2#

在这一点上,推荐的和python3兼容的方法是遵循python2到3指南:http://python-future.org/func_annotations.html

def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:
    """Embezzle funds from account using fake receipts."""
    pass

成为:

def embezzle(self, account, funds = 1000000, *fake_receipts):
    """Embezzle funds from account using fake receipts."""
    pass
embezzle.__annotations__ = {'account': str, 'funds': int, 'fake_receipts': str, 'return': None}
a11xaf1n

a11xaf1n3#

下面是我写的一个函数,用于解析Python 2的类型注解,并获取输入类型和返回类型的元组。它需要一些工作来处理类型库中的复杂类型定义(Any,Optional,List等):

class InvalidTypeHint(Exception):
    pass    

PYTHON_2_TYPE_HINT_REGEX = "\s*#\s*type:\s*(\(.+\))\s*->\s*(.+)\s*"

def parse_python_2_type_hint(typehint_string):
    # type: (str) -> (tuple, type)
    pattern = re.compile(PYTHON_2_TYPE_HINT_REGEX)
    search_results = pattern.search(typehint_string)
    if not search_results:
        raise InvalidTypeHint('%s does not match type hint spec regex %s' % (typehint_string, PYTHON_2_TYPE_HINT_REGEX))
    arg_types_str = search_results.group(1)
    return_type_str = search_results.group(2)
    try:
        arg_types_tuple = eval(arg_types_str)
        assert isinstance(arg_types_tuple, tuple)
        return_type = eval(return_type_str)
        assert isinstance(return_type, type)
    except Exception as e:
        raise InvalidTypeHint(e)
    return arg_types_tuple, return_type

def parse_arg_types_for_callable(func):
    # type:(callable)->tuple
    """

    :param func:
    :return: list of parameter types if successfully parsed, else None
    """

    # todo make this compatible with python 3 type hints
    # python 2.7 type hint
    source_lines = inspect.getsource(func).split("\n")
    def_statements = 0
    for source_line in source_lines:
        try:
            arg_types_tuple, return_type = parse_python_2_type_hint(source_line)
            return arg_types_tuple
        except InvalidTypeHint:
            if source_line.strip().startswith("def "):
                def_statements += 1
            if def_statements > 1:
                return None

相关问题