If you're ever learning Python, just remember this one thing:

Jul 17, 2006 17:07

If you're ever doing a foreach style iteration over a collection a la for object in objects:, object isn't a pointer or a reference, but a copy of what was in your collection. If you can remember this, you'll save yourself a couple hours of bashing your head on the wall and wondering where the hell your data was going ( Read more... )

pain, python, work, programming

Leave a comment

Comments 3

annodomini July 18 2006, 01:36:13 UTC
Well, I wouldn't say that you're getting a copy of the object; there is no copying going on, other than (potentially) the copying of the pointer to the object. Basically, every object has an identity and a value; the value can be mutable or immutable. The identity would be implemented as a pointer for compound objects, but for simple objects like numbers, is just the number itself. Some objects like numbers and strings are immutable, while others like lists are mutable. When you do a foreach style iteration, the identity of object is the same as the identity of one of the items in the list, so copying certainly isn't happening.

Now, you also have names that refer to these objects. There can be many different names that refer to the same object, and a name can refer to different objects at different times. When you perform assignment, or binding, you don't change the identity of any particular object, and you don't mutate any objects, you change which object a particular name points to. This is how the object variable in a loop like ( ... )

Reply

hyuga July 18 2006, 03:06:02 UTC
Yeah, I figured out that I had to do like in your last example. And I know my wording wasn't quite right--I didn't mean to imply that the entire object was being copied. That would take way too long, especially for relatively large objects. Now that I look at it, I'm not sure what I meant--I still wasn't entirely sure what was going on.

I had a collection of objects of class Field and subclasses thereof, and I was trying to do something like this:

for field in fields:
    if field.name == 'foo': field = FieldSubclass(field.name)It's obvious to me now why that wouldn't have done any good ( ... )

Reply


archaicangel July 18 2006, 04:02:41 UTC
You know.. I have no idea what you mean when you post things like this... but I *do* know alot of people who do this kind of thing and hardly any of them will ever give advice on how to fix things. And if I ever get into programming, I can always look back on your posts to save myself lots of headaches :p

Reply


Leave a comment

Up