Python 2中的类型提示

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

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代码:

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

等效于以下内容:

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

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

2izufjch

2izufjch2#

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

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

成为:

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

a11xaf1n3#

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

  1. class InvalidTypeHint(Exception):
  2. pass
  3. PYTHON_2_TYPE_HINT_REGEX = "\s*#\s*type:\s*(\(.+\))\s*->\s*(.+)\s*"
  4. def parse_python_2_type_hint(typehint_string):
  5. # type: (str) -> (tuple, type)
  6. pattern = re.compile(PYTHON_2_TYPE_HINT_REGEX)
  7. search_results = pattern.search(typehint_string)
  8. if not search_results:
  9. raise InvalidTypeHint('%s does not match type hint spec regex %s' % (typehint_string, PYTHON_2_TYPE_HINT_REGEX))
  10. arg_types_str = search_results.group(1)
  11. return_type_str = search_results.group(2)
  12. try:
  13. arg_types_tuple = eval(arg_types_str)
  14. assert isinstance(arg_types_tuple, tuple)
  15. return_type = eval(return_type_str)
  16. assert isinstance(return_type, type)
  17. except Exception as e:
  18. raise InvalidTypeHint(e)
  19. return arg_types_tuple, return_type
  20. def parse_arg_types_for_callable(func):
  21. # type:(callable)->tuple
  22. """
  23. :param func:
  24. :return: list of parameter types if successfully parsed, else None
  25. """
  26. # todo make this compatible with python 3 type hints
  27. # python 2.7 type hint
  28. source_lines = inspect.getsource(func).split("\n")
  29. def_statements = 0
  30. for source_line in source_lines:
  31. try:
  32. arg_types_tuple, return_type = parse_python_2_type_hint(source_line)
  33. return arg_types_tuple
  34. except InvalidTypeHint:
  35. if source_line.strip().startswith("def "):
  36. def_statements += 1
  37. if def_statements > 1:
  38. return None
展开查看全部

相关问题