On Tue, Jun 28, 2011 at 11:21 AM, Bináris <wikiposta@gmail.com> wrote:

2011/6/28 Morten Wang <nettrom@gmail.com>

2: Using functions instead of strings as the replacement in sub().  If you're looking to do a fair amount of conditional logic in your replacement, it might be more easily written by having a function do it, rather than attempt to do it all with a regex.

Does the couple replace.py + fixes.py allow me to use own functions in replacements? I don't want to lose the comfort of replace.py, it is well written.

As far as I can tell from looking at the code, the replacement is done by replaceExcept() in textlib.py, and the documentation there clearly states that you can use a function for replacing (there's a check if the replacement is a callable function, and if it is that function is called, thus working the same way as re.sub() does).

The documentation in replace.py states that both parts of the tuple for replacement must be a string, which appears to contradict textlib.py, but I think that might be a bug.  While I haven't tested this, it appears to me that writing a function and referring to that should work.  Of course you'd have to test it to be sure.


Cheers,
Morten