[Baypiggies] identity cache / flywheel design pattern
Shannon -jj Behrens
jjinux at gmail.com
Sun Aug 3 03:57:23 CEST 2008
I've blogged about it here:
http://jjinux.blogspot.com/2008/08/python-intern.html
> i wonder if you have a newbie nugget here
> regardless of subsequent improvements: would you please explain what's
> going on in the two setdefault() statements that makes this work?
> what's being returned to s1 and then to s2?
The code is basically saying:
if identity_cache.has_key(s2):
s2 = identity_cache[s2] # Get the cached instance of the same value.
else:
identity_cache[s2] = s2 # Cache the instance.
s2 always has the same "value", but the above code makes sure there's
only *one copy* of that value.
> It sounds like a job for the "intern" built-in function
Bingo. Right you are! It makes the identity_cache completely
unnecessary.
> Curious that your signature referred to Lisp, which has used the
> intern concept for decades! ;-)
Proof positive that there's a lot about Lisp I don't know ;)
> BTW the pattern name is 'flyweight'
You know, when I read "flyweight" in the gang of four, I envisioned a
flywheel, and I could never figure out why they picked that name ;)
> But maybe that's still flyweight, just a really simple form of it.
I remember the example in the book was using a flyweight for character
objects. Hence, every 'a' would be the same instance.
Thanks guys!
More information about the Baypiggies
mailing list