views:

5184

answers:

6

Hello, i want to check whether variable exists. Now I'm doing something like this:

try:
   myVar
except NameError:
   # Doint smth

Are there any other ways without exceptions? Or is that part of code right?

+2  A: 

catch is called except in Python. other than that it's fine for such simple cases. There's the AttributeError that can be used to check if an object has an attribute.

SilentGhost
Sorry, i forgot that. Corrected.
Ockonal
A: 

Python assumes that you've assigned the variable to something, worst case you've assigned it the None object.

great_llama
no Python doesn't assume such thing.
SilentGhost
Read your link again, that's not what it's saying.
Kiv
+26  A: 

To check the existence of a local variable:

if 'myVar' in locals():
  # myVar exists.

To check the existence of a global variable:

if 'myVar' in globals():
  # myVar exists.

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.
Ayman Hourieh
Ok, and how can i check attribute existing in class?
Ockonal
and how do you turn the name of variable that possibly doesn't exist into a string?
SilentGhost
@SilentGhost, can you elaborate more or give an example?
Ayman Hourieh
'myVar' is a str, myVar is variable name. OP doesn't seem to have 'myVar'.
SilentGhost
But the OP is typing the code, they can type 'myVar' intstead of myVar.If the variable name is not known when the code is written, it will be stored in a string variable at runtime, and the check I posted will also work.
Ayman Hourieh
+4  A: 

The use of variables that haven't been defined is actually a bad thing in any language since it indicates that the logic of the program hasn't been thought through properly.

Python will assume you know what you're doing (otherwise you'd be using VB :-).

The following trick, which is similar to yours, will ensure that a variable has some value before use:

try:
    myVar
except NameError:
    myVar = None
# Now you're free to use myVar without Python complaining.
paxdiablo
+1: if you don't know your variables, you are just writing buggy code on purpose.
S.Lott
+2  A: 

Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.

For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:

my_variable = None

def InitMyVariable():
  global my_variable
  if my_variable is None:
    my_variable = ...
Paul Hankin
+1: Just use exceptions.
S.Lott
+1: It's better to ask forgiveness than to take permission.
muhuk
A: 

A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:

# Search for entry.
for x in y:
  if x == 3:
    found = x

# Work with found entry.
try:
  print('Found: {0}'.format(found))
except NameError:
  print('Not found')
else:
  # Handle rest of Found case here
  ...