473,785 Members | 2,746 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help Understanding weakref (lazyloader)

I found this script at http://www.pygame.org/wiki/LazyImage...arent=CookBook
And I can't quite figure out how it works. I was wondering if someone
could clarify it for me.
The Code is:

import pygame
import weakref

class ResourceControl ler(object):
def __init__(self, loader):
self.__dict__.u pdate(dict(
names = {},
cache = weakref.WeakVal ueDictionary(),
loader = loader
))

def __setattr__(sel f, name, value):
self.names[name] = value

def __getattr__(sel f, name):
try:
img = self.cache[name]
except KeyError:
img = self.loader(sel f.names[name])
self.cache[name] = img
return img
class ImageController (ResourceContro ller):
def __init__(self):
ResourceControl ler.__init__(se lf, pygame.image.lo ad)
My question is why does the __setattr__ set the value to
self.names[name] instead of self.cache[name]?
Sep 4 '08 #1
1 1372
On Sep 3, 10:46*pm, Ripter <Ripter...@gmai l.comwrote:
I found this script athttp://www.pygame.org/wiki/LazyImageLoadin g?parent=CookBo ok
And I can't quite figure out how it works. I was wondering if someone
could clarify it for me.
The Code is:

import pygame
import weakref

class ResourceControl ler(object):
* * def __init__(self, loader):
* * * * self.__dict__.u pdate(dict(
* * * * * * names = {},
* * * * * * cache = weakref.WeakVal ueDictionary(),
* * * * * * loader = loader
* * * * ))

* * def __setattr__(sel f, name, value):
* * * * self.names[name] = value

* * def __getattr__(sel f, name):
* * * * try:
* * * * * * img = self.cache[name]
* * * * except KeyError:
* * * * * * img = self.loader(sel f.names[name])
* * * * * * self.cache[name] = img
* * * * return img

class ImageController (ResourceContro ller):
* * def __init__(self):
* * * * ResourceControl ler.__init__(se lf, pygame.image.lo ad)

My question is why does the __setattr__ set the value to
self.names[name] instead of self.cache[name]?
I feel stupid, I figured it out. (Don't program while watching Back to
the Future)
The reason would be the 'lazy' part. self.names holds the file name,
and when you get the property back (__getattr__) it checks to see if
it already got the value or not, and uses the name to get the value if
it hasn't already.

Duh. Sorry.
Sep 4 '08 #2

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

Similar topics

1
2627
by: Ames Andreas (MPA/DF) | last post by:
Hi all, I'm using python 2.1 and can't easily upgrade (Zope). I'm using the Queue module to synchronize/communicate between two threads and weakref.proxy objects to avoid cycles. Scenario: thread1: - is the sole consumer (non-blocking get) - holds the reference to the queue
1
2000
by: Mathias Mamsch | last post by:
Hi, I have some confusion concerning the weakref module. I am trying to save a weak reference to a bound member function of a class instance for using it as a callback function. But I always get dead references, when I try to create a reference to a bound member function. It seems as if an instance of a class owns no reference to its memberfunctions, so the the reference count is always zero. How can I come behind that?
2
2085
by: Mike C. Fletcher | last post by:
I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). Looking at the docs for 2.3's weakref.ref, there's no mention of whether the callbacks are held with a strong reference. My experiments suggest they are not... i.e. I'm trying to use this pattern: class Closer( object ): """Close the OIDStore (without a __del__)""" def __init__( self, btree ): """Initialise the...
2
2846
by: Chua Wen Ching | last post by:
Hi, Is there any place that i can learn the basics of IL and using ILDASM. I saw the internet but there is not much to see and read. Maybe i didn't search deep enough. I prefer if someone can recommend me some URL than book recommendations if possible. Thanks :) Yeah, i want to know how IL works behind the scene.
0
1086
by: bearophileHUGS | last post by:
This is yet another memoize decorator, it's meant to be resilient (and fast enough): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466320 Like most memoize decorators it stores the pairs of data-result in cache dictionary, but Garrett Rooney says: it could be better if it used the new weak references from python 2.1. The way it works now, the cached values will be stored forever, and will never be garbage collected. This is...
3
5636
by: TonyHa | last post by:
Hello I try to install boost_1_33_1 on RedHat Linux. I have downloaded boost into /user/dtgtools/tmp and I try to install it into /user/dtgtools/packages/boost. I use the following commands: export PYTHON_ROOT="/user/dtgtools/packages/python/2.5"
2
2766
by: John Nagle | last post by:
Is there some way to get a strong ref to the original object back from a weakref proxy object? I can't find any Python function to do this. ".ref()" doesn't work on proxy objects. John Nagle
3
2026
by: Odalrick | last post by:
I'm trying to write a simple game and decided I need an eventmanager. <code> import weakref from collections import defaultdict class _EventManager( object ): def __init__( self ): self._handled_events = defaultdict( weakref.WeakKeyDictionary )
6
2875
by: George Sakkis | last post by:
I'm baffled with a situation that involves: 1) an instance of some class that defines __del__, 2) a thread which is created, started and referenced by that instance, and 3) a weakref proxy to the instance that is passed to the thread instead of 'self', to prevent a cyclic reference. This probably sounds like gibberish so here's a simplified example: ==========================================
0
9643
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10319
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10087
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7496
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.