在ipython中使用re模块时,我发现没有记录 template
功能:
In [420]: re.template?
Type: function
Base Class: <type 'function'>
String Form: <function template at 0xb7eb8e64>
Namespace: Interactive
File: /usr/tideway/lib/python2.7/re.py
Definition: re.template(pattern, flags=0)
Docstring:
Compile a template pattern, returning a pattern object
还有一面旗帜 re.TEMPLATE
和它的别名 re.T
。
在2.7或3.2的文档中都没有提到这一点。他们在做什么?它们是早期版本的Python过时的宿醉,还是未来可能正式添加的实验性功能?
在CPython 2.7.1中, re.template()
被定义为 如:
def template(pattern, flags=0):
"Compile a template pattern, returning a pattern object"
return _compile(pattern, flags|T)
_compile
电话 _compile_typed
哪个叫 sre_compile.compile
。代码中唯一的地方 T
(又名 SRE_FLAG_TEMPLATE
)检查标志是 在那个功能:
elif op in REPEATING_CODES:
if flags & SRE_FLAG_TEMPLATE:
raise error, "internal: unsupported template operator"
emit(OPCODES[REPEAT])
skip = _len(code); emit(0)
emit(av[0])
emit(av[1])
_compile(code, av[2], flags)
emit(OPCODES[SUCCESS])
code[skip] = _len(code) - skip
...
这会产生禁用所有重复操作符的效果(*
, +
, ?
, {}
等等):
In [10]: re.template('a?')
---------------------------------------------------------------------------
.....
error: internal: unsupported template operator
代码的结构方式(无条件的 raise
在一堆死代码之前)让我觉得该功能要么从未完全实现,要么由于某些问题而被关闭。我只能猜出预期的语义可能是什么。
最终结果是该函数没有任何用处。
我不知道这个函数是做什么的,但是至少早在2.3版本的sre.py文件中就已经存在了代码,代码仍然有这个注释:
# sre extensions (experimental, don't rely on these)
T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
我会远离他们。