find isset() php function equivalent in python

  • Thread starter Olivier Noblanc ATOUSOFT
  • Start date
M

Max M

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


--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
 
O

Ola Natvig

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top