Max said:
Ola said:
try:
if variable:
# isset
pass
except NameError:
# not set
pass
you could use:
But be aware that it is bad bad practice to do it like that.
If you need variables that you don't know that name of, you should put
them in a dictionary. They are made for that exact purpose.
unkown_vars = {}
unkown_vars['variable'] = 42
'variable' in unkown_vars
True
If it's a greater possibility that the 'variable' are set than it's not
you will get better performance when using:
try:
print unknown_vars['variable']
except KeyError:
print 'variable are not set'
istead of
if 'variable' in unknown_vars:
print unknown_vars['variable']
else:
print 'variable are not set'
You could even use
print unknown_vars.get('variable', 'variable are not set')
dictionary.get(key, default) returns the default if key are not located
in the dictionary, I'm not sure if the function uses the try / except
KeyError aproach or what it uses.