function to check whether a variable already exists?

Remco Gerlich scarblac at pino.selwerd.nl
Tue May 1 19:37:48 CEST 2001


Graham Guttocks <graham_guttocks at yahoo.co.nz> wrote in comp.lang.python:
> 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.

I don't think it can be done, in general, without invoking a load of black
magic.

And it looks like a weird construct - *why* do you need this?! Surely you
have control over where your variables are initialized? And is that a global?

Can't you at least set it to None at the top of the program and test for that?

If the variable is in some module, you can test for hasattr(module,"NEWSRC").

Or store globals like this in some dictionary, and use dict.has_key("NEWSRC").

-- 
Remco Gerlich



More information about the Python-list mailing list