variables exist
Steven Bethard
steven.bethard at gmail.com
Mon Apr 11 14:42:12 EDT 2005
Brian van den Broek wrote:
> Fredrik Lundh said unto the world upon 2005-04-11 10:14:
>> "fabian" wrote:
>>> how testing if a variable exists in python as isset in php??
>>
>> try:
>> variable
>> except NameError:
>> print "variable not set"
>>
>> but that is really lousy Python; better make sure you always assign to
>> all variables, and use None (or another suitable value) to mark that some
>> variable has no meaningful content right now.
>>
>> that is, instead of
> <SNIP full try/except example>
>> write
>>
>> variable = None
>> if condition:
>> variable = 1
>> ...
>> if variable is None:
>> print "variable not set"
>
> I'm a hobbyist and still learning, but the claim the try/except is
> "lousy Python" surprise me a bit. The try/except way seems like an
> instance of "Easier to ask Forgiveness than Permission", and my sense
> is that in 95% of cases that approach is widely considered more Pythonic
> than LBYL (of which the suggested idiom seems reminiscent).
>
> As it happens, most of my code does preset names to None, but reading
> this thread made me wonder. Are you suggesting setting to None is
> better as it makes explicit that there is nothing there, but this may
> change in the future? (This is why I do it.) Or for some other reason?
I had a similar reaction to Fredrik's statement. In general, I wouldn't
call a try/except solution lousy style, as long as the path through
except was sufficiently "exceptional". That is, for code like:
if condition_that_happens_99_percent_of_the_time:
variable = 1
try:
variable
except NameError:
print "variable not set"
seems perfectly reasonable to me, because the exception is caught in the
*exceptional* case. However, if one case isn't clearly the exceptional
one, then it probably doesn't makes sense to use an exception, and I'd
write it like:
variable = None
if condition_that_happens_40_percent_of_the_time:
variable = 1
...
if variable is None:
print "variable not set"
Actually, I typically refactor my code so that I can write situations
like this as:
if condition_that_happens_40_percent_of_the_time:
variable = 1
...
else:
print "variable not set"
But the point still stands. If the variable being unset really is an
exceptional case, use an exception. If it's not, then an if/else block
is probably the better way to go.
STeVe
More information about the Python-list
mailing list