Descriptors · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. Which of these makes an object a data descriptor?
2. What does this print?
class Counter:
    def __init__(self):
        self.count = 0
    def __get__(self, instance, owner):
        if instance is None:
            return self
        self.count += 1
        return self.count

class Widget:
    clicks = Counter()

a, b = Widget(), Widget()
print(a.clicks, b.clicks, a.clicks)
3. What does this print?
class D:
    def __get__(self, instance, owner):
        return 'descriptor'
    def __set__(self, instance, value):
        pass

class C:
    x = D()

c = C()
c.__dict__['x'] = 'instance'
print(c.x)
4. What does this print?
class D:
    def __get__(self, instance, owner):
        return 'descriptor'

class C:
    x = D()

c = C()
c.__dict__['x'] = 'instance'
print(c.x)
5. For obj.attr, in which order does Python consider the possible sources?
6. What does this print?
class D:
    def __get__(self, instance, owner):
        return 'got it'

class C:
    pass

c = C()
c.d = D()
print(c.d == 'got it')
7. When is a descriptor's __set_name__ called?
8. What does this print?
import gc, weakref

class Node:
    pass

n = Node()
r = weakref.ref(n)
before = r() is n
del n
gc.collect()
print(before, r() is None)
9. Which of these objects can be used as a key in a weakref.WeakKeyDictionary?
10. A data descriptor stores values with setattr(instance, self.name, value) in its __set__, where self.name is the descriptor's own attribute name. What happens on assignment?
11. What does this print?
class T:
    @property
    def value(self):
        return 'computed'

t = T()
t.__dict__['value'] = 'stored'
print(t.value)
12. What does this print?
class P:
    def f(self):
        return 1

p = P()
print(p.f is p.f, p.f.__func__ is P.f, p.f.__self__ is p)

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Data or non-data?

Write descriptor_kind(obj) that classifies an object the way attribute lookup does:

- 'data' if it is a data descriptor (its type has __get__ and also __set__ or __delete__) - 'non-data' if its type has __get__ but neither __set__ nor __delete__ - None if it isn't a descriptor at all

Check the object's type, not the object itself: Python looks special methods up on the type, so a __get__ stored as an instance attribute doesn't count.

Hints (2)
  1. Start with cls = type(obj) and use hasattr(cls, '__get__').
  2. Check for __set__ or __delete__ to decide between data and non-data.
Show a solution
def descriptor_kind(obj):
    cls = type(obj)
    if not hasattr(cls, '__get__'):
        return None
    if hasattr(cls, '__set__') or hasattr(cls, '__delete__'):
        return 'data'
    return 'non-data'

Exercise 2: A reusable validated attribute

Write a data descriptor Positive for numeric attributes that must be greater than zero.

- Use __set_name__ to learn the attribute name. - __set__ raises ValueError if the value isn't an int or float (reject bool), or if it is not > 0. The message must contain the attribute name, e.g. 'width must be positive'. - Store the value in the instance's __dict__ under the attribute's own name. - __get__ returns the descriptor itself for class access, the stored value for instance access, and None if no value was set yet.

The Rectangle class in the starter shows how it's used.

Hints (3)
  1. __set_name__(self, owner_class, name) runs when Rectangle is created; save name on self.
  2. Write with instance.__dict__[self.name] = value, not setattr, or you'll recurse forever.
  3. isinstance(True, int) is True, so check for bool first.
Show a solution
class Positive:
    def __set_name__(self, owner_class, name):
        self.name = name

    def __set__(self, instance, value):
        if isinstance(value, bool) or not isinstance(value, (int, float)):
            raise ValueError(f'{self.name} must be a number')
        if value <= 0:
            raise ValueError(f'{self.name} must be positive')
        instance.__dict__[self.name] = value

    def __get__(self, instance, owner_class):
        if instance is None:
            return self
        return instance.__dict__.get(self.name)


class Rectangle:
    width = Positive()
    height = Positive()

    def __init__(self, width, height):
        self.width = width
        self.height = height

Exercise 3: Leak-free storage for slotted classes

Some classes use __slots__ and have no instance __dict__, so a descriptor must keep their values itself.

Write a data descriptor Tracked that stores each instance's value in the descriptor, in a weakref.WeakKeyDictionary named values, so that destroyed instances don't stay in memory.

- __get__ returns the descriptor for class access, and the instance's value (or None if unset) otherwise. - __set__ stores the value for that instance.

The starter uses a plain dict, which leaks. Also fix the Sensor class: it uses __slots__, and as written its instances can't be weakly referenced.

Hints (2)
  1. weakref.WeakKeyDictionary() is a drop-in replacement for {} here.
  2. A class with __slots__ supports weak references only if '__weakref__' is one of the slots.
Show a solution
import weakref

class Tracked:
    def __init__(self):
        self.values = weakref.WeakKeyDictionary()

    def __set__(self, instance, value):
        self.values[instance] = value

    def __get__(self, instance, owner_class):
        if instance is None:
            return self
        return self.values.get(instance)


class Sensor:
    __slots__ = ('serial', '__weakref__')
    reading = Tracked()

Exercise 4: A compute-once attribute

Write a non-data descriptor lazy that can decorate a method, like functools.cached_property:

- The first time the attribute is read on an instance, call the decorated function with the instance, store the result in the instance's __dict__ under the same name, and return it. - On later reads the instance dictionary should be found before the descriptor, so the function isn't called again. (That's why lazy must not define __set__.) - Class access returns the descriptor itself.

Deleting the attribute from the instance (del obj.attr) should make the next read compute it again.

Hints (2)
  1. Use __set_name__ to learn the attribute name (or use self.func.__name__).
  2. After computing the value, store it with instance.__dict__[name] = value. Because lazy is a non-data descriptor, the next lookup finds the instance entry first.
Show a solution
class lazy:
    def __init__(self, func):
        self.func = func

    def __set_name__(self, owner_class, name):
        self.name = name

    def __get__(self, instance, owner_class):
        if instance is None:
            return self
        value = self.func(instance)
        instance.__dict__[self.name] = value
        return value