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?
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?
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.
Python assumes that you've assigned the variable to something, worst case you've assigned it the None object.
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.
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.
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 = ...
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
...