views:

2260

answers:

6

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP.

if condition:
    a = 42

# is a defined here?

if other_condition:
    del a

# is a defined here?
+1  A: 
try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope
sri
disregard that, ...
Brandon Thomson
+10  A: 
try:
  thevariable
except NameError:
  print "well, it WASN'T defined after all!"
else:
  print "sure, it was defined."

Despite the unexplained downvotes, try/except/else is nevertheless the right way to handle anomalous situations in Python. If you trust the anonymous, silent downvoters more than you trust me, go ahead and do it wrong; otherwise, you might want to consider this suggestion as it deserves!-)

Alex Martelli
Your solution is wrong because the premise of the question is wrong: you shouldn't be in a situation where you don't know if a variable is defined.
Aaron Gallagher
@Aaron: There are many cases when you don't know whether variable is defined. You can refactor code to avoid this in many, but not all cases. Alex's solution is correct and it the best when refactoing is not possible for some reasons. There is not much information in the question, so I believe only person asked it can select the best way to handle his case.
Denis Otkidach
@Denis: I see that you are much more optimistic than I am.
Aaron Gallagher
@Denis Otkidach: If there are *any* cases where you don't absolutely know if a variable is defined, you have a broken design.
S.Lott
@Aaron, "should" is a 4-letter word -- e.g. no driver "should" ever exceed the speed limit, but that doesn't mean you don't take all proper and needed precautions against those who nevertheless do. Maintaining fragile, undertested legacy code with somewhat-broken design that you inherited from somebody else is a fact of life, and those who can only think of big-bang rewriting from scratch rather than cautiously and incrementally need to re-read Joel's 9-years-old essay http://www.joelonsoftware.com/articles/fog0000000069.html .
Alex Martelli
@S.Lott People use it to maintain backwards compatibility. Search for NameError in Python 3.1 source code. There are many instances where "try: var_name except NameError: something_else" is used. Here are a couple of place where it is used: CSV (http://svn.python.org/projects/python/trunk/Lib/csv.py) library and in the ElementTree library (http://svn.python.org/projects/python/trunk/Lib/xml/etree/ElementTree.py).
sri
This debate is much more interesting that the answer itself, which by the way is 100% correct and let you handle poor legacy code elegantly.
e-satis
+4  A: 

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)

gnibbler
+9  A: 

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42
swillden
If you like to do it that way you should make the initial value unique so you can distinguish from something setting `a` to `None` ie. `UNDEFINED=object();a=UNDEFINED` then you can test with `a is not UNDEFINED`
gnibbler
This is a common use of None. It's literally the semantic meaning of None-- it's nothing, nada, zip. It exists, but has "no value". Using a non-None value is useful if None can come up in an assignment and so on, but this is not so common that avoiding None should be standard practice. For example, in the question, a would only ever be 42 or undefined. Changing undefined to having a value of None results in no loss of information.
Devin Jeanpierre
+4  A: 

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.

Denis Otkidach
+7  A: 

The correct answer to the question, "How do I discover if a variable is defined in python?" is the not-very-useful but entirely-pythonic answer:

Read the source file starting at the point where you want to discover if a variable is defined, going up in the file to the start of the source file. If you don't see the variable defined, then it is not defined.

To answer the real question you're asking, "Why is it not obvious how to deal with the situation where I have used the del keyword?"

Don't use the del keyword. It is not useful.

Jerub
This solution (reading) does not quite get around conditional defining. I'm not judging your "don't use del" advice, I'm just downvoting the first two paragraphs of your answer.
Emilio M Bumachar