checking whether a var is empty or not

Dave Benjamin ramen at lackingtalent.com
Wed Aug 4 12:08:36 EDT 2004


In article <ap%Pc.22247$%r.245331 at nasal.pacific.net.au>, Dave Cole wrote:
> Dave Benjamin wrote:
>>
>> No, in PHP, you can find out if a variable exists using isset(). And trying
>> to dereference an uninitialized variable will generate a warning if you have
>> error reporting turned up all the way (error_reporting(E_ALL)).
> 
> >>> def isset(var):
> ...     return var in globals()
> ...
> >>> print isset('var')
> 0
> >>> var = 43
> >>> print isset('var')
> 1
> 
> Not that I can see any good use for this :-).

Not that there's *any* reason to do anything like this, *ever* ;) but...

>>> import inspect
>>> def isset(v):
...     return v in globals() or v in inspect.currentframe().f_back.f_locals
...
>>> isset('a')
False
>>> a = 5
>>> isset('a')
True
>>> def f():
...     b = 6
...     print isset('b')
...     print isset('c')
...
>>> f()
True
False
>>> c = 42
>>> f()
True
True

Verdict: Just catch the NameError, already! =)

-- 
  .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

"When the country is confused and in chaos, information scientists appear."
Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html



More information about the Python-list mailing list