Menu

#4 unexpected behavior of re.sub() function in GUESS console

open
nobody
None
5
2009-10-19
2009-10-19
Dmitry D
No

Recently I tried to do some regex pattern replacement in the python script I use with GUESS.
I imported 're' module and tried to use re.sub() function.

Surprisingly re.sub() function did not work as expected in GUESS console:
>>> re.sub('0', '1', '0')
Traceback (innermost last):
File "<string>", line 1, in ?
File "c:\projects\guess\src\Lib\sre.py", line 63, in sub
File "c:\projects\guess\src\Lib\sre.py", line 164, in _sub
File "c:\projects\guess\src\Lib\sre.py", line 185, in _subn
TypeError: call of non-function ('string' object)

I did some investigation and found the problem:
According to python manual the second argument of re.sub() may be either string or callable object used to produce replacement string.

In regular python shell string is not a callable object:
>>> callable('1')
False

However, in GUESS console string for some reason is callable:
>>> callable('1')
1

Because of this implementation of re._subn() in $GUESS_HOME\src\Lib\sre.py" does not work:
-----------
def _subn(pattern, template, string, count=0):
# internal: pattern.subn implementation hook
if callable(template):
filter = template
else:
template = _compile_repl(template, pattern)
def filter(match, template=template):
return sre_parse.expand_template(template, match)
...
-----------

It seems that something is wrong with the version of Jython used with GUESS: I ran the same code in the most recent Jython (v2.5.1) and got the expected result.

The obvious workaround is to always use function as the second argument of re.sub(), e.g.:
>>> re.sub('0', lambda x:'1', '0')
1

But it would be nice to figure out what makes string callable in GUESS - it may introduce hard-to-catch errors in the code relying on the fact that python string is not a callable object.

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.