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?

2
  • 1
    Your function won't work, because you are passing a variable to your function which doesn't exist. Otherwise your code is okay. Commented May 1, 2016 at 7:08
  • Possible duplicate of How do I check if a variable exists? Commented Apr 3, 2019 at 20:37

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, you point about stack frames is a thing I couldn't even consider. +1
This is one of several possible solutions. There are more here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.