Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.
-
Upload
eleanore-lester -
Category
Documents
-
view
214 -
download
0
Transcript of Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.
Weak References in Python 2.1
Fred L. Drake, Jr.
PythonLabs @ Digital Creations
What are References?
• Pointers to values– Python name bindings– PyObject* variables in C extensions
Do References have Flavors?
• Strong References– All references in Python code– “Owned” PyObject* references in C
• Borrowed References– Un-owned PyObject* references in C
• Require great care when handled in C
• Typically have a short lifespan
So why Weak References?
• Variety is spice…
• Weak refs allow another way to interact with an object’s lifespan– Actions can be attached to object lifespan
without having to control it– Object can be shared among multiple users
without affecting lifespan
What do they look like?
>>> import weakref
>>> o = {}
>>> ref = weakref.ref(o)
>>> ref()
{}
>>> del o # no more dict!
>>> ref()
None
Can they be proxy objects?
>>> import weakref
>>> o = {}
>>> ref = weakref.proxy(o)
>>> ref.items()
[]
You didn’t “del o”…
>>> del o # no more dict!
>>> ref.items()
Traceback (most recent call last):
File "<stdin>", line 1
ReferenceError: ...
What else is there?
• WeakKeyDictionary– Similar to java.util.WeakHashMap– When value is only useful while key is live
• WeakValueDictionary– When value can be shared among unrelated
components but discarded when no one is using it
Isn’t that just caching?
• Yes!
• Clients no longer need to tell the cache it’s done with the object– Less obtrusive cache APIs lead to…– Cleaner client code
What can I use it with?
• Any class instance
• Extension types with explicit support– What other types do you want to use it with?
Tell me: [email protected]
?