Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

11
Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations

Transcript of Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

Page 1: 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

Page 2: 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

Page 3: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

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

Page 4: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

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

Page 5: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

What do they look like?

>>> import weakref

>>> o = {}

>>> ref = weakref.ref(o)

>>> ref()

{}

>>> del o # no more dict!

>>> ref()

None

Page 6: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

Can they be proxy objects?

>>> import weakref

>>> o = {}

>>> ref = weakref.proxy(o)

>>> ref.items()

[]

Page 7: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

You didn’t “del o”…

>>> del o # no more dict!

>>> ref.items()

Traceback (most recent call last):

File "<stdin>", line 1

ReferenceError: ...

Page 8: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

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

Page 9: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

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

Page 10: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

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]

Page 11: Weak References in Python 2.1 Fred L. Drake, Jr. PythonLabs @ Digital Creations.

?