Ignore NameError while iterating
I need to iterate over a list and perform some operation (say for example sum
). Whenever it receives a NameError value, it should simply skip that variable and return the remaining result set.
a = 1
b = 2
c = 3
try:
z = sum([a, b, c, d])
except NameError as e:
pass
else:
print(z)
I haven't declared d
here, so when an exception is caught, you just need to skip d
and calculate the remaining result. How to do it?
Expected result = 6
NOTE. I have explicitly named a, b, c, d for understanding, but in a real scenario, the list is populated differently.
source to share
Seeing how you get into undefined variables helps a lot, but one way is to parse the traceback to get the variable name undefined and assign it a default value of 0:
def f():
a = 1
b = 2
c = 3
while True:
try:
z = sum([a, b, c, d])
break
except NameError as e:
name = e.message.split()[1].strip("'")
exec "{} = {}".format(name, 0)
return z
print(f())
For python 3, exec will not work, so you will need to add the name to the globals:
def f():
a = 1
b = 2
c = 3
while True:
try:
z = sum([a, b, c, d])
break
except NameError as e:
name = str(e).split()[1].strip("'")
globals()[name] = 0
return z
source to share
When NameError
raised, the function sum
will not be completed. Here's one way to get around this. This is a weird approach, but since you have a special situation it might help.
a = 1
b = 2
c = 3
def checkExists(variable):
return variable in locals() or variable in globals()
toCheck = []
# Check all the variables as strings to see if they exist
for var in ["a", "b", "c", "d"]:
# If they do, add them to the 'check' list
if checkExists(var):
toCheck.append(eval(var))
print(sum(toCheck))
source to share