473,396 Members | 1,858 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Another method of lazy, cached evaluation.

Recently, I needed to provide a number of game sprite classes with
references to assorted images.

I needed a class to:
- allow instances to specify which image files they need.
- ensure that a name should always refer to the same image.
- only load the image if it is actually used.

After some messing about, I came up with this:
class LazyBag(object):
def __init__(self, function):
self.__dict__["function"] = function
self.__dict__["arguments"] = {}

def __setattr__(self, key, args):
try:
existing_value = self.arguments[key]
except KeyError:
existing_value = args
if existing_value != args:
raise ValueError("Attribute must retain its initial value,
which is %s." % str(self.arguments[key]))
self.arguments[key] = args

def __getattr__(self, key):
args = self.arguments[key]
r = self.__dict__[key] = self.function(*self.arguments[key])
del self.arguments[key]
return r
This class lets me do something like this:

cache = LazyBag(Image.open)

cache.pic_1 = "data/pic_1.png"
cache.pic_2 = "data/pic_2.png"
Now, when the pic_1 and pic_2 attributes are accessed, they will return
an Image instance, which is something different to which they were
initially assigned. Is this kind of behavior bad form? Likewise, what
do people think about raising an exception during an assignment
operation?

Is there a correct name for this sort of class? 'LazyBag' doesn't sound
right...
-Sw.

Jan 18 '06 #1
3 1057

si**********@gmail.com wrote:
Now, when the pic_1 and pic_2 attributes are accessed, they will return
an Image instance, which is something different to which they were
initially assigned. Is this kind of behavior bad form?
That's pretty good, I like it.
Likewise, what
do people think about raising an exception during an assignment
operation?


I prefer to use the 'if key in dict' idiom, but I know some others
prefer your method.

I foresee 2 difficulties, neither earth shattering:

1. Speed might be an issue - on prior projects, my speed tests showed
that overriding getattr and setattr slowed the program down by quite a
bit.

2. I see you are caching the loaded picture, but I would choose a
different bag than __dict__. I would create a dict called cache in the
class to store it in, to avoid possible name conflicts where the stat
name has the same name as the png (which is unlikely, I realize.)

A potential enhancement would be to have some sort of cleanup, to where
if a picture is not being used by any assignment statement, it would
drop off. Or perhaps a 'force cleanup' where it clears out all the
cache, which would force the 'loadimage' routine to run again the next
time the picture is referenced.

Good job!

--Kamilche

Jan 19 '06 #2
If you wanted to avoid the __getattr__ __setattr__ speed hit, something
like this would work. However, you have to not mind calling a function
to get the data, instead of only getting the attribute:

class Cache(object):
_cache = {}
def __init__(self, filename):
self.filename = filename
def Get(self):
obj = self._cache.get(self.filename, None)
if not obj:
obj = self._cache[self.filename] = Load(self.filename)
return obj
@staticmethod
def Clear():
print "\nClearing cache\n"
Cache._cache = {}

class Sprite(Cache):
def Draw(self):
print self.Get()

class Sound(Cache):
def Play(self):
print self.Get()

def Load(filename):
print "********** Open '%s' here" % filename
suffix = filename.lower()[-3:]
if suffix in ['png', 'bmp', 'jpg', 'tif']:
tag = 'Image'
elif suffix in ['wav', 'mp3']:
tag = 'Sound'
return "%s data from %s" % (tag, filename)
def main():
sprite1 = Sprite('data/pic_1.png')
sprite2 = Sprite('data/pic_2.png')
sound1 = Sound('data/sound_22.wav')

sprite1.Draw()
sprite2.Draw()
sound1.Play()
sprite1.Draw()
sprite2.Draw()
sound1.Play()

Cache.Clear()

sprite1.Draw()
sprite2.Draw()
sound1.Play()
sprite1.Draw()
sprite2.Draw()
sound1.Play()

main()

Jan 19 '06 #3
Hmm, good ideas.

I've made some refinements and posted to the cookbook. The refinements
allow for multilple function arguments and keywords.

http://aspn.activestate.com/ASPN/Coo.../Recipe/466315

-Sw.

Jan 19 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
by: Steven Bethard | last post by:
So I end up writing code like this a fair bit: map = {} for key, value in sequence: map.setdefault(key, ).append(value) This code basically constructs a one-to-many mapping -- each value that...
4
by: SL33PY | last post by:
Hi again, I've been coding in vb .Net on my most recent project and during a debug session I noticed that VB .Net hasn't got lazy evaluation... WHY?! I love lazy evaluation and actually count on...
9
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by...
39
by: Boltar | last post by:
Why does C do lazy evaluation for logical boolean operations but not bitwise ones? Ie: the following program prints "1 2" , not "1 1" under gcc main() { int a = 1; int b = 1; 0 && ++a;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.