On Sat, Jul 22, 2006 at 01:41:17PM -0400, Kent Johnson wrote: > Dave Kuhlman wrote:
[snip] > > And, also, that's why the following statements all have exactly > > the same effect: > > > > total = 5 > > locals()['total'] = 5 > > exec('total = 5') > > You're not in the mood to believe the docs today, eh? Yes, locals() > returns a dict and yes, you can modify it. And yes, "changes may not > affect the values of local variables used by the interpreter." In > particular modifying locals() inside a function doesn't do what you > think it will: > > In [14]: def badlocals(): > ....: locals()['total'] = 5 > ....: print total > ....: > > In [15]: badlocals > Out[15]: <function badlocals at 0x00E4AEB0> > > In [16]: badlocals() > --------------------------------------------------------------------------- > exceptions.NameError Traceback (most > recent call last) > > F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console> > > F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console> in > badlocals() > > NameError: global name 'total' is not defined Good lord. I feel queasy. I think I just felt the ground move under me. (We in California near the fault line are sensitive that way.) What is the explanation of this? > > At global scope, locals() == globals() and modifying it affects the > global namespace. In function scope, I believe locals() is actually a > copy of the real namespace. Ah. I see. A copy, eh? Or, at least a new dictionary separate from the "real" namespace. OK. I don't know why locals() returns a copy as opposed to the original, but at least that explains the results of the example you give. And, the sickening feeling of dread has gone away, the feeling or dread one has when the fundamental structure of the (Python) world has been turned upside down. Thanks for correcting me and for clarification. And, looks like Lloyd was right. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor