python中的re.template函数有什么作用?
在使用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留下的过时功能,还是可能在未来正式添加的实验性特性?
1 个回答
16
在 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
),让我觉得这个功能要么从来没有完全实现过,要么因为某些问题被关闭了。我只能猜测它原本的设计意图是什么。
最终的结果是这个函数没有任何实用的功能。