python newbie - question about lexical scoping

Tim Roberts timr at probo.com
Sat Dec 1 19:59:14 EST 2007


Matt Barnicle <mattb 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()
>    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?

Is that REALLY what the code looks like?  Or does it actually look like
this:

  comments = []
  comment = models.comment()
  for row in rows:
      comment.author = row[1]
      comment.text = row[0]
      comments.append(comment)

That construct would produce exactly the result you describe.  You would
also get the result you describe if models.comment() were a normal function
that returns a single object, instead of a class name, as I have assumed.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list