function to check whether a variable already exists?

Lyle Johnson ljohnson at resgen.com
Tue May 1 13:42:42 EDT 2001


> 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.

Well, there are some issues of which scope you're talking about, but if you
want to see if it's defined in the global scope, you could do this:

    if not globals().has_key("NEWSRC"):
        NEWSRC = os.path.expanduser("~/.newsrc")

or if you're looking at a particular object, try using hasattr():

    if not hasattr(obj, "NEWSRC"):
        NEWSRC = os.path.expanduser("~/.newsrc")

Hope this helps,

Lyle





More information about the Python-list mailing list