Storing objects required by functions.

John Roth newsgroups at jhrothjr.com
Tue Dec 30 16:11:54 CET 2003


"David M. Wilson" <dw-google.com at botanicus.net> wrote in message
news:99dce321.0312300655.14c5a8db at posting.google.com...
> 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
>
>
> # 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()
>
>
> # 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*
> :)

Your second solution (the one you labeled "horrible and probably
slow") is a classic example of a Function Object, and it's described
that way in "Design Patterns". AFAIK, it's got the same call overhead
as any other way of doing the job. I'd call it the cleanest way of doing
a parameterized function.

John Roth
>
>
> David.






More information about the Python-list mailing list