"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"
</F>
Hi Fredrik and all,
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 have no partisan interests either way; I'm just trying to understand. Thanks and best,
Brian vdB
-- http://mail.python.org/mailman/listinfo/python-list