FAQ
I have a function with some params including some data to be used with
re.sub and some other data which i want to use in the replacement.

I can provide re.sub with a callable, but this will only be called
with a match object, it's not possible to give it any of the other
params.

The solution I came up with to tackle this is with some funny globals,
which doesnt feel 'right':

--------------------------------------------------------------------------------------
import re

def test(data,pre,post):
p = re.compile("([0-9])")
global _pre, _post
_pre = pre
_post = post

def repl(m):
global _pre, _post
return _pre + m.group(1) + _post

print p.sub(repl, data)
test("number 1 test", "->", "<-")
number ->1<- test
--------------------------------------------------------------------------------------

Is there any other way to do this?

cheers,

Guyon Mor?e
http://gumuz.looze.net/

Search Discussions

  • Guyon Morée at Dec 30, 2005 at 5:26 am
    Thanks, I just *assumed* I needed the globals to reach the vars in the
    nested function.

    This makes my code a l ot cleaner :)

    cheers,
    Guyon Mor?e
    http://gumuz.looze.net/
  • Skip at Dec 30, 2005 at 5:26 am
    Guyon> The solution I came up with to tackle this is with some funny
    Guyon> globals, which doesnt feel 'right':

    ...

    Guyon> Is there any other way to do this?

    You've almost got it right. Just lose the "global":

    def test(data, pre, post):
    p = re.compile("([0-9])")

    def repl(m):
    return pre + m.group(1) + post

    print p.sub(repl, data)

    For a full explanation, google for "python nested scopes".

    Skip
  • Fredrik Lundh at Dec 30, 2005 at 9:48 am

    "Guyon Mor?e wrote:

    I can provide re.sub with a callable, but this will only be called
    with a match object, it's not possible to give it any of the other
    params.

    The solution I came up with to tackle this is with some funny globals,
    which doesnt feel 'right':

    --------------------------------------------------------------------------------------
    import re

    def test(data,pre,post):
    p = re.compile("([0-9])")
    global _pre, _post
    _pre = pre
    _post = post

    def repl(m):
    global _pre, _post
    return _pre + m.group(1) + _post

    print p.sub(repl, data)
    contemporary python (nested scopes):

    def test(data,pre,post):
    p = re.compile("([0-9])")
    def repl(m):
    return pre + m.group(1) + post
    print p.sub(repl, data)

    old python (object binding):

    def test(data,pre,post):
    p = re.compile("([0-9])")
    def repl(m, pre=pre, post=post):
    return pre + m.group(1) + post
    print p.sub(repl, data)

    </F>

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedDec 30, '05 at 5:07a
activeDec 30, '05 at 9:48a
posts4
users3
websitepython.org

People

Translate

site design / logo © 2022 Grokbase