passed extra info to repl function

Tim Peters tim.one at home.com
Mon Oct 29 15:38:17 EST 2001


[Michael P. Soulier]
>     I'm using Python's re.sub() function, with the replace part
> of the call being a function, to parse a template. The idea is to have
> a dictionary of keywords with the corresponding replacement strings, and
> then doing one big call of re.sub(), to replace all keywords with their
> replacement strings.
> ...
> Now, replacement_dict is obviously a global in this module. That's the
> problem. I need it because I can't pass any extra information to
> replace, as it only accepts a match object. Unfortunatly, using a single
> global like this prevents the user of this class from instantiating
> multiple instances of this object without potentially conflicting with
> overlapping use of the global replacement_dict variable.
>
>     I'm using Python 1.5.2, so I can't use nested scopes to get
> around this.

Luckily, they were never necessary.  You *could* abuse default arguments to
sneak replacement_dict into the arglist of your replace function, but it's
straightforward to use a bound method instead:

class Replacer:
    def __init__(self, dict):
        self.dict = dict

    def replace(self, matchobj):
        key = matchobj.group(1)
        if self.dict.has_key(key):
             return self.dict[key]
        else:
             return ''

import re
thisone = Replacer({'a': 'AA', 'c': 'CC'}).replace
print re.sub('([abcd])', thisone, 'abcdefg')

That prints AACCefg.

> I'd like replace to be able to access an instance variable of
> self.replacement_dict, so that all replacement dictionaries are
> unique to the class instance, but the scoping rules prevent
> replace from seeing the self reference.
>
>     Any ideas from the experienced?

Use a bound method, as above.  Then all instance vrbls are available within
the replace function.





More information about the Python-list mailing list