NameError: how to get the name?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Apr 24 08:07:39 EDT 2010


On Sat, 24 Apr 2010 04:19:43 -0700, Yingjie Lan wrote:

> 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()



-- 
Steven



More information about the Python-list mailing list