【问题标题】:Is it possible to type-hint a compiled regex in python?是否可以在 python 中键入提示已编译的正则表达式?
【发布时间】:2016-11-28 03:16:01
【问题描述】:

我想对预编译和存储的正则表达式列表使用自动补全,但我似乎无法导入 _sre.SRE_Pattern 类,而且我无法以编程方式提供从 type( ) 到格式的注释 # type: classname 或将其用于返回 -> 类名样式提示

有没有办法从 _sre.c 东西中显式导入一个类?

【问题讨论】:

标签: python regex type-hinting


【解决方案1】:

您应该使用专门添加到打字模块中的typing.Pattern and typing.Match 以适应此用例。

例子:

from typing import Pattern, Match
import re

my_pattern = re.compile("[abc]*")  # type: Pattern[str]
my_match = re.match(my_pattern, "abbcab")  # type: Match[str]
print(my_match)

【讨论】:

  • 看起来 pycharm 还没有完全理解打字模块,但看起来这就是它应该的工作方式。
  • Pycharm 肯定会抱怨并抱怨 re.compile 的 Type 是 _Regex(而不是 typing.Pattern 或 typing.Pattern[str])
  • 请注意 typing 是在 3.5 中添加的,因此您的代码将在 3.4 或更早版本上引发运行时错误。
  • @EdwardNedHarvey -- 你可以通过 pip 安装 typing 模块来解决这个问题。它可作为 Python 2.7 和 3.3+ 的反向端口使用。
  • @TonySuffolk66 __Regex 似乎是 PyCharm 中的一个内部“骨架”,当 PyCharm 可以确定您有 re.compile 的结果时,它会自动应用,但我没有看到任何方法实际使用它作为源代码中的类型提示来启用代码完成。
猜你喜欢
  • 2017-01-13
  • 2013-01-23
  • 1970-01-01
  • 2010-09-09
  • 2018-07-29
  • 1970-01-01
  • 2018-07-30
  • 2017-11-15
  • 2021-11-26
相关资源
最近更新 更多