python newbie - question about lexical scoping

Matt Barnicle matthew at wageslavery.org
Sat Dec 1 19:40:17 EST 2007


> On Dec 1, 4:47 pm, Matt Barnicle <ma... at wageslavery.org> wrote:
>> hi everyone..  i've been chugging along learning python for a few months
>> now and getting answers to all needed questions on my own, but this one
>> i can't figure out nor can i find information on the internet about it,
>> possibly because i don't understand the right words to type into
>> google..
>>
>> i have a very common scenario and need to know the python way to do it.
>> take this example loop:
>>
>> comments = []
>> for row in rows:
>>     comment = models.comment()
>
> Insert here:
>       print type(comment), id(comment), repr(row[:2])
>
>>     comment.author = row[1]
>>     comment.text = row[0]
>>     comments.append(comment)
>>
>> the problem is that when i go to retrieve the comments later, they are
>> all the same object!  i assume this is due to there being no lexical
>> scoping?  so what is the solution to this?
>
> And the attributes of the "same object" match the first two elements
> of which input row:
> (a) rows[0]
> (b) rows[-1]
> (c) some other row
> (d) you can't tell because all input rows have the same value in each
> of row[0] and row[1]
> (e) none of the above?
>
> It's nothing to do with lexical scoping, at least in the code that
> you've shown us, which has no apparent problems. You need to show us
> the code for the models.comment function/method/class. Possibly it is
> returning the same object each time it is invoked (answer (b) above);
> the above print statement will help investigate that possibility, plus
> the possibility that the objects are not the same objects, but are
> different objects with the same attributes (answer (d) above). Also
> show us the code for retrieving the comments later; possibly you are
> retrieving the same element of the comments list each time. Use this:
>     print [id(x) for x in comments]
> to verify your assertion that they are all the same object.
>
> Cheers,
> John

aye yaye aye...  thanks for the pointers in the right direction..  i
fiddled around with the code for a while and now i've reduced it to the
*real* issue...  i have a class dict variable that apparently holds its
value across instantiations of new objects..  the problem can be
illustrated in the following much simpler code:

>>> class foo():
...     bar = { 'baz': 'bing' }
...
>>> a = foo()
>>> a.bar
{'baz': 'bing'}
>>> a.bar['baz'] = 'bong'
>>> a.bar
{'baz': 'bong'}
>>> b = foo()
>>> b.bar
{'baz': 'bong'}





More information about the Python-list mailing list