Storing objects required by functions.

Bengt Richter bokr at oz.net
Tue Dec 30 19:08:47 EST 2003


On 30 Dec 2003 06:55:27 -0800, dw-google.com at botanicus.net (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
>
There is another way, but IMO it would be nice to be able to have an optional
second parenthesized list to make bindings the same way which wouldn't be part
of the call signature. I.e.,

    def uses_default_parm_yuck(x)(r = re.compile("...")):
        pass

or, same thing more prominently:

    def uses_default_parm_yuck(x)(
        # pre-bound locals
        r = re.compile("...")
    ):
        pass

ISTM most of the implementation pieces for that should already be there.

The other way is to take advantage of functions' roles as decriptors and the mechanism that
makes bound methods with a self as the first arg, but the rest apparently normal. I.e,
we can put the r parameter in the place of self (not specifically tested)

    def uses_self(r, x):
        pass
    uses_self = uses_self.__get__(re.compile("..."))

then (the rebound) uses_self will look like a bound method and want exactly one parameter x
(or whatever signature you program) and be able to refer to r like self.

>
>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*
>:)
>
>
>David.

Regards,
Bengt Richter




More information about the Python-list mailing list