NameError: how to get the name?

Steven D'Aprano steve at
Sat Apr 24 14:07:39 CEST 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
    locals()['x'] = 2

A better approach would be:

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

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

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

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


More information about the Python-list mailing list