How do I modify my callers local variables?

Jeremy Hylton jeremy at alum.mit.edu
Mon Feb 12 17:05:41 EST 2001


>>>>> "AD" == Andreas Dietrich <andreas.dietrich at news.online.de> writes:

  AD> def parse_keywords(defaults,kw):
  AD>     import sys try:
  AD>         raise None
  AD>     except:
  AD>         frame = sys.exc_info()[2].tb_frame.f_back
  AD>         locals_dict=frame.f_locals
  AD>     for i in defaults.keys():
  AD>         try:
  AD>             locals_dict[i]=kw[i]
  AD>         except KeyError:
  AD>             try:
  AD>                 locals_dict[i]=defaults[i]
  AD>             except KeyError:
  AD> 	        #We should not be here
  AD>                 print 'Moo. Moo'
  AD>     return

  AD> def test(**kw):
  AD>     parse_keywords({'a':1,'b':2,'c':3},kw)
  AD>     #didn't work
  AD>     print a,b,c

  AD> test()

  AD> Unfortunately it doesn't work.  Is there a way to do it?  I'm
  AD> tired of the repetitious code involved in keyword parsing.

There is no way to do it.  If there were, it would be tempting to
disable it <0.5 wink>.

  AD> I'd really appreciate any insights into this matter.

When test() is compiled, the compiler determines that a, b, and c are
all global variables.  The body of test() does not contains
assignments or other name binding operations.

If you want to have default arguments for local variables, I suggest
using ... default arguments!

def test(a=1, b=2, c=3):
    print a, b, c

Jeremy




More information about the Python-list mailing list