variables exist
Michael J. Fromberger
Michael.J.Fromberger at Clothing.Dartmouth.EDU
Sun Apr 17 18:14:08 EDT 2005
In article <9622d535.0504110552.1e070e8d at posting.google.com>,
fabian.steels at free.fr (fabian) wrote:
> how testing if a variable exists in python as isset in php??
>
Would the following be a satisfactory implementation?
def isset(varname, lloc = locals()):
return varname in lloc or varname in globals()
I believe this works as desired:
>>> x = 5
>>> def f(y):
... z = 10
... print isset('z') ## ==> True
... print isset('y') ## ==> True
... print isset('x') ## ==> True
...
Tests:
>>> f(1) ## As shown above
>>> print isset('z') ## ==> False
>>> print isset('y') ## ==> False
>>> print isset('x') ## ==> True
>>> print isset('varname') ## ==> False
>>> print isset('lloc') ## ==> False
>>> lloc = "foo!"
>>> print isset('lloc') ## ==> True
Perhaps this is not the most elegant solution, but I believe it handles
scoping correctly.
-M
--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
More information about the Python-list
mailing list