Creating an object that can track when its attributes are modified

Ben Sizer kylotan at gmail.com
Wed Mar 6 19:26:57 EST 2013


On Thursday, 7 March 2013 00:07:02 UTC, Steven D'Aprano  wrote:
> On Wed, 06 Mar 2013 08:56:09 -0800, Ben Sizer wrote:
> 
> > I need to be able to perform complex operations on the object that may
> > modify several properties, and then gather the properties at the end as
> > an efficient way to see what has changed and to store those changes. Any
> > comparison of before-and-after snapshots could work in theory, but in
> > practice it could be expensive to produce the snapshots on larger
> > objects and probably expensive to calculate the differences that way
> > too. Performance is important so I would probably just go for an
> > explicit function call to mark an attribute as having been modified
> > rather than trying to do a diff like that. (It wouldn't work for
> > rollbacks, but I can accept that.)
> 
> Premature optimization.
> 
> Unless you have been eating and breathing Python code for 15+ years, your 
> intuition of what is expensive and what isn't will probably be *way* off. 
> I've been using Python for ~15 years, and I wouldn't want to try to guess 
> what the most efficient way to do this will be.

I admit, I've only been using Python for 10 years, but I've learned a lot about optimisation and what needs optimising from my time as a game developer. This code needs to be fairly high-performing due to the role it plays in my server and the frequency with which the behaviour gets called.

> Actually I lie. I would guess that the simple, most obvious way is 
> faster: don't worry about storing what changed, just store *everything*. 
> But I could be wrong.

The use case I have is not one where that is suitable. It's not the snapshots that are important, but the changes between them.

> Fortunately, Python development is rapid enough that you can afford to 
> develop this object the straightforward way, profile your application to 
> see where the bottlenecks are, and if it turns out that the simple 
> approach is too expensive, then try something more complicated.

I don't see a more straightforward solution to the problem I have than the one I have posted. I said that a system that took snapshots of the whole object and attempted to diff them would probably perform worse, but it would probably be more complex too, given the traversal and copying requirements. 

-- 
Ben Sizer



More information about the Python-list mailing list