function to check whether a variable already exists?

Alex Martelli aleaxit at yahoo.com
Tue May 1 15:13:35 EDT 2001


"Graham Guttocks" <graham_guttocks at yahoo.co.nz> wrote in message
news:mailman.988735442.13417.python-list at python.org...
> Can anyone tell me how to wrap the following in a function as to
> avoid typing this try, except sequence for every variable whose
> existence I want to check?
>
> For example,
>
> try:
>     if NEWSRC:pass
> except NameError:
>     NEWSRC = os.path.expanduser("~/.newsrc")
>
> It seems tricky, because you can't just pass a function NEWSRC because
> if it doesn't first exist NameError will immediately be raised.

No, but you _can_ pass 'NEWSRC' -- the quotes are what allows that!

So, specifically:
    if vars().has_key('NEWSRC'):
        # the variable exists
works.  Wrapping it in a _function_ is harder, because you need to
have the function identify the caller's vars(), and if the function needs
to bind the variable among the caller's locals() in particular, it may
be close to unfeasible or require too much "black magic".


Alex






More information about the Python-list mailing list