[Edu-sig] self within re.sub

David Niergarth jdnier@execpc.com
Wed, 07 Feb 2001 12:17:08 -0600


on 2/6/01 5:06 PM, Bruno Vernier at vernier@vc.bc.ca wrote:

> I am stuck with this issue while building the python embeded wiki pages:
> 
> how do I pass "self" to the  method in re.sub and keep the match variable?
>
> here is the simplified code:
> 
> rpython = rexec.REexec()
> 
> sub process(match):
> ctag = match.groups()
> # process here requires stuff from self,
> #   namely rpython.r_eval(content of py element)
> return #evaluated python or latex snippets
> 
> pattern = '(py|python|latex|sql)'
> tag = re.compile(pattern)
> text = "<py>x=3;y=2</py> <latex>\x</latex> <py>x=4</py> <latex>\x</latex>"
> text = tag.sub(process,text)

If I understand what your asking... You can pass the rpython instance into
the replace function as a default argument. For example,

  text = tag.sub(lambda m, instance=rpython: process(m, instance), text)

and change process() to expect a second argument. If the instance exists
before you define process(), you could skip the lambda and define process as

  def process(match, instance=rpython):
      # do useful stuff
      return # evaluated python or latex snippets

  text = tag.sub(process, text)

Also, Python 2.1alpha2 has added nested scopes, which should allow you to
avoid having to use default arguments. See
http://python.sourceforge.net/peps/pep-0227.html for details.

--David