NameError: how to get the name?

Y

Yingjie Lan

I wanted to do something like this:

while True:
try:
def fun(a, b=b, c=c): pass
except NameError as ne:
name = get_the_var_name(ne)
locals()[name] = ''
else: break

What's be best way to implement the function
get_the_var_name(ne) that returns the name
of the variable that could not be found?

Thanks in advance,

Yingjie
 
S

Steven D'Aprano

I wanted to do something like this:

while True:
try:
def fun(a, b=b, c=c): pass
except NameError as ne:
name = get_the_var_name(ne)
locals()[name] = ''
else: break

This won't work. Writing to locals() does not actually change the local
variables. Try it inside a function, and you will see it doesn't work:

def test():
x = 1
print(x)
locals()['x'] = 2
print(x)

A better approach would be:

try:
b
except NameError:
b = ''
# and the same for c

def fun(a, b=b, c=c):
pass


Better still, just make sure b and c are defined before you try to use
them!


What's be best way to implement the function get_the_var_name(ne) that
returns the name of the variable that could not be found?


'name' in locals()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,174
Messages
2,570,940
Members
47,486
Latest member
websterztechnologies01

Latest Threads

Top