Storing objects required by functions.

David M. Wilson dw-google.com at botanicus.net
Tue Dec 30 09:55:27 EST 2003


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


David.




More information about the Python-list mailing list