In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to