--- On Sat, 4/24/10, Gary Herron <[email protected]> wrote:
> From: Gary Herron <[email protected]>
> Subject: Re: NameError: how to get the name?
> To: 
> Cc: [email protected]
> Date: Saturday, April 24, 2010, 8:03 PM
> Yingjie Lan wrote:
> > --- On Sat, 4/24/10, Steven D'Aprano <[email protected]>
> wrote:
> > 
> >   
> >> From: Steven D'Aprano <[email protected]>
> >> Subject: Re: NameError: how to get the name?
> >> To: [email protected]
> >> Date: Saturday, April 24, 2010, 4:07 PM
> >> 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:
> >> 
> >>     

No it DOESN'T work, and both of you are precisely correct.
Just for playing around, I substituted 
"locals()" by "globals()" and it worked as desired:

============================================
def wrapfun():
   while True:
     try: print a
     except: globals()['a']="HERE YOU ARE"
     else: break
     finally: print globals()['a']
wrapfun()
============================================

Thanks for the information! BTW, why would 
locals() and globals() differ in this respect?
For example:

============================================
def wrapfun():
   while True:
     try: print a
     except: locals()['a']="HERE YOU ARE"
     else: break
     finally: print locals()['a']
wrapfun()
============================================

That would print "HERE YOU ARE" infinitely.
Apparently, the dict gets modified, but is
not the same as the one actually used to
resolve name 'a' in the statement 'print a'.

Yingjie


      
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to