[Tutor] Sometimes unreferenced!?
Jeff Shannon
jeff@ccvcorp.com
Fri Feb 7 15:26:03 2003
John Abbe wrote:
> At 9:23 AM -0800 on 2003-02-06, Jeff Shannon typed:
>
>> The trick is that the parser examines every variable in a function as
>> it's reading in the def, and decides at that time whether a variable
>> is local or global.
>
>
> Okay, i understand *that* this is happening (and thanks for the fix),
> but i don't get why. If the parser can know that groupData is a global
> variable and thus not choke on groupData.reverse(), then why can't it
> know that groupData is a global variable when the function tries to
> look up its contents?
Because the parser doesn't know whether you intend the groupData in the
function to be the same groupData as the global one. You may be working
in a large program, and not even realize that there *is* a global
variable by the same name. Python has decided that any variable that is
created (i.e. the name is bound/re-bound) in a function is something
that might or might not be intentionally different from any similar name
in the global scope. So rather than guessing that you want to use the
global, and possibly changing something that you don't expect and which
will be very difficult to track down, Python throws an exception as a
way of asking you to clarify just what your intent is. On the other
hand, when you use a name that doesn't exist in the local scope (as in
your first function), then Python decides that it's safe to assume that
you know that the name exists in a containing (i.e., global) scope, so
it looks there.
I hope this clarifies things -- I know that it helps *me* a lot to
understand just *why* a particular behavior is the way it is, it makes
it much easier to remember and to predict other related behaviors...
Jeff Shannon
Technician/Programmer
Credit International