[Tutor] Sometimes unreferenced!?
John Abbe
johnca@ourpla.net
Fri Feb 7 05:17:01 2003
At 9:23 AM -0800 on 2003-02-06, Jeff Shannon typed:
>John Abbe wrote:
>
>>def f():
>> records = [4, 5]
>> groupData += records
>
>>UnboundLocalError: local variable 'groupData' referenced before assignment
>
>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.
>
>In your first function e(), you modify the object that groupData
>points to, by calling its reverse() method. But it's still the same
>list object, so there's no re-binding, so groupData is considered a
>global name. This means that Python looks it up properly at runtime.
>
>In your f() function, though, you use += to create a *new* list
>(which is the union of groupData and records), and then re-bind
>groupData to point to that new list. Here's where things get tricky
>-- Python sees the re-binding before running the code, so it
>presumes that groupData is a local variable here.
>So a new, local name is created that shadows the global groupData.
>Now, 'groupData += records' is (loosely) equivalent to 'groupData =
>groupData + records', so Python tries to look up the contents of the
>(local) groupData variable to add them to the contents of the
>'records' variable -- but at this point, the local version of
>groupData doesn't point to anything yet.
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?
Life,
John
--
All you /\/\ John Abbe "If you don't like the news,
need \ / CatHerder go out and make some of your own."
is... \/ http://ourpla.net/john/ --Wes Nisker