Project 4 · Practice

Quiz & exercises

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

Quiz

1. What does this print?
class Field:
    def __set_name__(self, owner, name):
        self.name = name

class A:
    pass

A.x = Field()
B = type('B', (), {'x': Field()})
print(hasattr(A.x, 'name'), hasattr(B.x, 'name'))
2. What does this print?
class Bounded:
    def __init__(self, min_=None):
        self.min_ = min_
    def __set_name__(self, owner, name):
        self.name = name
    def __set__(self, instance, value):
        if self.min_ and value < self.min_:
            raise ValueError(f'{self.name} too small')
        instance.__dict__[self.name] = value
    def __get__(self, instance, owner):
        return self if instance is None else instance.__dict__.get(self.name)

class Account:
    balance = Bounded(0)

a = Account()
a.balance = -5
print(a.balance)
3. What does type('Point', (), {'x': 0}) return?
4. Why does the solution check values with isinstance(value, numbers.Integral) instead of type(value) is int?
5. What does this print?
import unittest

class T(unittest.TestCase):
    def test_values(self):
        for v in (1, 2, 3):
            with self.subTest(v=v):
                self.assertLess(v, 2)

result = unittest.TestResult()
T('test_values').run(result)
print(result.testsRun, len(result.failures))
6. In the refactored design, IntegerField(BaseValidator) defines only validate. Why is it still a data descriptor?
7. What does this print?
class Base:
    def __set_name__(self, owner, name):
        self.name = name
    def validate(self, value):
        pass
    def __set__(self, instance, value):
        self.validate(value)
        instance.__dict__[self.name] = value
    def __get__(self, instance, owner):
        return self if instance is None else instance.__dict__.get(self.name)

class Even(Base):
    def validate(self, value):
        if value % 2:
            raise ValueError('odd')

class C:
    n = Even()

c = C()
for v in (2, 3, 4):
    try:
        c.n = v
    except ValueError:
        pass
print(c.n)

Coding exercises

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

Exercise 1: Goal 1: IntegerField

Write a data descriptor IntegerField(min_=None, max_=None):

- It learns its attribute name with __set_name__. - Assigning a value that isn't a numbers.Integral raises ValueError. - If min_ is not None, values below it raise ValueError; if max_ is not None, values above it raise ValueError. Both bounds are inclusive, and either may be None (no limit). - Every ValueError message contains the attribute name. - Valid values are stored in the instance __dict__ under the attribute's own name. - Class access returns the descriptor; reading a value that was never set returns None.

Hints (3)
  1. Check bounds with self._min is not None and value < self._min; a plain truthiness test skips a bound of 0.
  2. Store with instance.__dict__[self.prop_name] = value, and read with instance.__dict__.get(self.prop_name).
  3. In __get__, return self when instance is None.
Show a solution
import numbers

class IntegerField:
    def __init__(self, min_=None, max_=None):
        self._min = min_
        self._max = max_

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

    def __set__(self, instance, value):
        if not isinstance(value, numbers.Integral):
            raise ValueError(f'{self.prop_name} must be an integer.')
        if self._min is not None and value < self._min:
            raise ValueError(f'{self.prop_name} must be >= {self._min}.')
        if self._max is not None and value > self._max:
            raise ValueError(f'{self.prop_name} must be <= {self._max}.')
        instance.__dict__[self.prop_name] = value

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

Exercise 2: Goal 2: CharField

Write a data descriptor CharField(min_=None, max_=None) for string attributes:

- Non-strings raise ValueError. - Strings shorter than min_ or longer than max_ characters raise ValueError (bounds are inclusive; max_=None means no maximum). - A min_ of None or a negative number is stored as 0 in the attribute _min; max_ is stored as given in _max. - Error messages contain the attribute name; values are stored in the instance __dict__ under the attribute name. - Class access returns the descriptor; an unset value reads as None.

Hints (2)
  1. max(min_ or 0, 0) turns both None and negative numbers into 0.
  2. Compare len(value) with the bounds, and remember self._max may be None.
Show a solution
class CharField:
    def __init__(self, min_=None, max_=None):
        self._min = max(min_ or 0, 0)
        self._max = max_

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

    def __set__(self, instance, value):
        if not isinstance(value, str):
            raise ValueError(f'{self.prop_name} must be a string.')
        if len(value) < self._min:
            raise ValueError(f'{self.prop_name} must be >= {self._min} chars.')
        if self._max is not None and len(value) > self._max:
            raise ValueError(f'{self.prop_name} must be <= {self._max} chars.')
        instance.__dict__[self.prop_name] = value

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

Exercise 3: Goal 3: build test classes on the fly

To test a descriptor you need an owner class, and a fresh one per test so tests can't affect each other. Write make_instance(**fields):

- It creates a new class named 'TestClass' whose class attributes are the keyword arguments (typically descriptors), and returns an instance of it. - The descriptors' __set_name__ must be called with the attribute names, exactly as if the class had been written with a class statement.

For example, obj = make_instance(age=IntegerField(0, 10)) gives an object where obj.age = 5 works and type(obj).age is the descriptor.

The starter attaches the attributes to a class after creating it. Find out why that doesn't work and fix it.

Hints (2)
  1. __set_name__ runs only while a class is being created, so setattr afterwards is too late.
  2. type(name, bases, namespace) creates a class from a dictionary of attributes; fields already is that dictionary.
Show a solution
def make_instance(**fields):
    cls = type('TestClass', (), fields)
    return cls()

Exercise 4: Goal 4: refactor onto a base class

IntegerField and CharField share most of their code. Refactor:

- BaseValidator(min_=None, max_=None) stores the bounds in _min and _max, implements __set_name__ (saving prop_name), __get__ (descriptor for class access, the stored value or None otherwise) and __set__, which calls self.validate(value) and then stores the value in the instance __dict__ under prop_name. Its own validate accepts everything. - IntegerField(BaseValidator) defines only validate (integral values within the optional bounds). - CharField(BaseValidator) defines __init__ (normalizing a None/negative minimum to 0, then calling super().__init__) and validate (strings within the optional length bounds).

Neither subclass may define __get__, __set__ or __set_name__. All errors are ValueErrors that mention the attribute name.

Hints (3)
  1. BaseValidator.__set__ needs just two lines: self.validate(value), then store.
  2. self.validate dispatches to the subclass's method, because self is the subclass instance.
  3. In CharField.__init__, compute the normalized minimum and pass it on with super().__init__(min_, max_).
Show a solution
import numbers

class BaseValidator:
    def __init__(self, min_=None, max_=None):
        self._min = min_
        self._max = max_

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

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

    def validate(self, value):
        pass

    def __set__(self, instance, value):
        self.validate(value)
        instance.__dict__[self.prop_name] = value


class IntegerField(BaseValidator):
    def validate(self, value):
        if not isinstance(value, numbers.Integral):
            raise ValueError(f'{self.prop_name} must be an integer.')
        if self._min is not None and value < self._min:
            raise ValueError(f'{self.prop_name} must be >= {self._min}.')
        if self._max is not None and value > self._max:
            raise ValueError(f'{self.prop_name} must be <= {self._max}.')


class CharField(BaseValidator):
    def __init__(self, min_=None, max_=None):
        super().__init__(max(min_ or 0, 0), max_)

    def validate(self, value):
        if not isinstance(value, str):
            raise ValueError(f'{self.prop_name} must be a string.')
        if len(value) < self._min:
            raise ValueError(f'{self.prop_name} must be >= {self._min} chars.')
        if self._max is not None and len(value) > self._max:
            raise ValueError(f'{self.prop_name} must be <= {self._max} chars.')