为避免此类错误,可以使用以下猴子补丁:
import re
re.sub = lambda pattern, repl, string, *, count=0, flags=0, _fun=re.sub: \
_fun(pattern, repl, string, count=count, flags=flags)
(*是禁止指定count,flags作为位置参数。_fun=re.sub是使用声明时间re.sub。)
演示:
$ python
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.sub(r'\b or \b', ',', 'or x', re.X)
'or x' # ?!
>>> re.sub = lambda pattern, repl, string, *, count=0, flags=0, _fun=re.sub: \
... _fun(pattern, repl, string, count=count, flags=flags)
>>> re.sub(r'\b or \b', ',', 'or x', re.X)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes 3 positional arguments but 4 were given
>>> re.sub(r'\b or \b', ',', 'or x', flags=re.X)
', x'
>>>