arxoft
arxoft

Reputation: 1475

Check if a variable exists

I am using following method isset(var) to determine if a variable exists.

def isset(variable):
    try:
        variable
    except NameError:
        return False
    else:
        return True

It returns True if variable exists. But if a variable doesn't exist I get following:

Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/home/lenovo/pyth/master/vzero/__main__.py", line 26, in <module>
    ss.run()
  File "vzero/ss.py", line 4, in run
    snap()
  File "vzero/ss.py", line 7, in snap
    core.display()
  File "vzero/core.py", line 77, in display
    stdout(session(username()))
  File "vzero/core.py", line 95, in session
    if isset(ghi): #current_sessions[user]):
NameError: global name 'ghi' is not defined

I don't want all these errors. I just want it return False. No output. How can I do this?

Upvotes: 3

Views: 7249

Answers (1)

warvariuc
warvariuc

Reputation: 59594

Instead of writing a complex helper function isset and calling it

if not isset('variable_name'):
    # handle the situation

in the place where you want to check the presence of the variable do:

try:
    # some code with the variable in question
except NameError:
    # handle the situation

Upvotes: 3

Related Questions