问题 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过时的宿醉,还是未来可能正式添加的实验性功能?


7757
2017-10-06 17:03


起源

Python开发者喜欢哪里 ncoghlan 什么时候需要它们? - agf
这在中描述 mail.python.org/pipermail/python-dev/2000-June/005143.html 我想你可能不得不问Frederik Lundh你是想知道它应该做什么或为什么它仍然在那里。 - Michael Hoffman


答案:


在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 在一堆死代码之前)让我觉得该功能要么从未完全实现,要么由于某些问题而被关闭。我只能猜出预期的语义可能是什么。

最终结果是该函数没有任何用处。


10
2017-10-06 17:24



感谢您的信息 - 在询问问题之前,我应该先看看来源。看起来很奇怪它仍然明确地导出了 __all__ 列出它唯一做的事情就是失败并出现异常。 - Dave Kirby


我不知道这个函数是做什么的,但是至少早在2.3版本的sre.py文件中就已经存在了代码,代码仍然有这个注释:

# sre extensions (experimental, don't rely on these)
T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking

我会远离他们。


2
2017-10-06 17:11



它的存在时间更长了 re的前身 sre。 - Sven Marnach
远离实验性功能是一个很好的建议,但这并没有回答这个问题,“re.template是什么 做?” - SingleNegationElimination