variables exist

Peter Otten __peter__ at web.de
Mon Apr 18 02:34:32 EDT 2005


Michael J. Fromberger wrote:

> 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

No, try it again in a fresh interpreter:

>>> def isset(name, loc=locals()):
...     return name in loc or name in globals()
...
>>> x = 5
>>> def f(y):
...     z = 10
...     print isset("x"), isset("y"), isset("z")
...
>>> f(42)
True False False
>>>

It may seem from the above that at least the global variable "x" is found
correctly, but beware, the global namespace where isset() is defined is
searched, not the one where it is called. Untested:

def isset(name):
    frame = sys._getframe(1)
    return name in frame.f_locals or name in frame.f_globals

might work, but is too magic for my taste.

Peter




More information about the Python-list mailing list