3

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?

arxoft
  • 1,385
  • 3
  • 17
  • 34
  • 1
    Your function won't work, because you are passing a variable to your function which doesn't exist. Otherwise your code is okay. – Ahsanul Haque May 01 '16 at 07:08
  • Possible duplicate of [How do I check if a variable exists?](https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists) – esmail Apr 03 '19 at 20:37

1 Answers1

3

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
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • Actually, you point about stack frames is a thing I couldn't even consider. +1 – Ahsanul Haque May 01 '16 at 07:36
  • This is one of several possible solutions. There are more [here](https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists) – LightCC Sep 21 '19 at 14:38