Storing objects required by functions.

Matt Goodall matt at pollenation.net
Tue Dec 30 16:38:15 CET 2003


David M. Wilson wrote:

>Further to my last post here, I was playing some more with building a
>regex object and storing it somewhere for use internally by a
>function. I'm not happy with any of my solutions:
>
>
># I don't like this, but the fact that you can modify the procedure's
># function via a named argument seems neat in a hacky sort of way.
>
>def uses_default_parm_yuck(x, r = re.compile("...")):
>    pass
>
>
>g = re.compile('...')
>
>def uses_global_yuck(x):
>    global g
>    pass
>  
>
There is no need to define g as global unless you actually need to 
rebind g inside the function.

>
># This is horrible and probably slow.
>
>class is_hex:
>    def __init__(self):
>        self.r = re.compile('...')
>
>    def __call__(self, x):
>        r = self.r
>        pass
>
>is_hex = is_hex()
>  
>
I doubt it's that much slower (if at all). You should profile it to check.

>
># This mucks up scoping so that your procedure can't access it's
># parent scope like it could normally. Since I never do this,
># it's my favourite.
>
>def is_hex():
>    r = re.compile('...')
>    def is_hex(s):
>        return r.match(s) is not None
>    return is_hex
>
>is_hex = is_hex()
>
>
>
>Am I missing something? Is there a nicer way of doing this? On a day
>to day basis I find myself in this situation quite regularly, and now
>I come to think of it today, it is something that I would like to
>improve.
>
>It is funny that in private it has never bothered me much, but when
>posting on comp.lang.python I find that the code is unacceptable.
>Maybe I have two modes of programming, idealist and practical? *shrug*
>:)
>
>
>David.
>  
>

Another alternative relies on the fact that functions themselves are 
objects so you could do this:

    def is_hex(s):
        return is_hex.r.match(s) is not None

    is_hex.r = re.compile(...)


Although, for simplicity, I would probably just make the compiled regex 
a module scope variable with a sensible name, maybe even using the _ 
prefix to hint that noone should touch it:

    _is_hex_regex = re.compile(...)

    def is_hex(s):
        return _is_hex_regex.match(s) is not None


Cheers, Matt

-- 
Matt Goodall, Pollenation Internet Ltd
w: http://www.pollenationinternet.com
e: matt at pollenation.net







More information about the Python-list mailing list