Existance of of variable

tiissa tiissa at nonfree.fr
Mon Jul 4 21:17:21 CEST 2005

Josiah Manson wrote:
> Hello. I am very new to Python, and have been unable to figure out how
> to check if a variable exists or not. In the following code I have made
> a kludge that works, but I think that it would be clearer to check if
> closest exists and not have to initialize it in the first place. How is
> that check done?

Variables are stored in two dictionnaries: globals() (for global 
variables) and locals() (for the local ones, which are also global on 
top level).

You can therefore write:

if 'closest' in locals():
     self.sel = [closest.name]

On the other hand, if you try to access a variable which doesn't exist, 
you'll get the NameError exception. Another way is then:

     self.sel = [closest.name]
except NameError:

> I also have a few other questions to tack on if you don't mind. I am
> setting dist to 1e9, because that is a larger value than any of the
> places in the galaxy will be far away. Is there a better way to
> initialize dist so that it is impossible for this to fail? For example,
> would setting dist to infinity work, and how is that done?

The float constructed from the string 'inf', float('inf'), may do the 
trick. I don't know the details, though.

  >>> 1e100 < float('inf')

> Extending my existance checking question, how does one check what type
> a variable has?

The '__class__' special attribute [1] will return the class. You can 
also look at the builtin 'isinstance' [2].

However, type checking is not a common idiom in python since we tend to 
use 'duck typing': if your object can do what you want with it, don't 
bother to check if it is exactly of the class you expect.
Therefore we often try to use the object then catch the exception rather 
than check the object then use it.

Of course, there may be situations where it's not suitable but type 
checking seems not to be too common in python.

[1] http://docs.python.org/lib/specialattrs.html
[2] http://docs.python.org/lib/built-in-funcs.html

More information about the Python-list mailing list