Variables and none?

Steve Holden steve at
Fri Jan 20 22:55:33 EST 2006

Ivan Shevanski wrote:
> Alright first of all I'd like to say I'm a python noob.
Welcome to

> Now that thats over with, heres what I'd like to know about.  Is there a 
> python way to detect if a variable exsists?  Say I had a program that 
> needed a certain variable to be set to run and the variable was not 
> found when it came time to use it. . .Would I just have to catch the 
> error, or could I have python look for the variable beforehand?
The usual way to do this is to catch the error.

If you can access the namespace of interest (say it's an instance of 
some class) then you can use hasattr() to answer the question, but 
catching the exception is the generic way to do it.

However, across a function call interface the usual way to allow values 
to not be provided by the caller is to provide a default value for the 
argument, such as

     def f(x, something=2):

That way if the caller just says


that's equivalent to

     f(33, something=2)

but it's also possible to say

     f(33, something=101)


     f(33, 101)

both of which are equivalent. Does this help at all?

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC           
PyCon TX 2006        

More information about the Python-list mailing list