Metaprogramming · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: A singleton metaclass ✓ Passed
Write a metaclass Singleton so that every class using it (directly or through inheritance) has at most one instance:
- calling the class a second time returns the same object; - each class gets its own instance, subclasses included; - __init__ runs only the first time the class is called.
Override __call__ in the metaclass.
class Singleton(type):
pass
def test_same_instance():
"""calling the class twice returns the same object"""
class Config(metaclass=Singleton):
pass
assert Config() is Config(), "two calls returned different objects"
def test_separate_classes():
"""two singleton classes have different instances"""
class A(metaclass=Singleton):
pass
class B(metaclass=Singleton):
pass
assert A() is not B()
assert type(A()) is A and type(B()) is B
def test_subclass_gets_own_instance():
"""a subclass has its own single instance"""
class Parent(metaclass=Singleton):
pass
class Child(Parent):
pass
p = Parent()
c = Child()
assert type(c) is Child, f"Child() returned a {type(c).__name__}"
assert c is Child() and p is Parent()
def test_init_runs_once():
"""__init__ runs only on the first call"""
calls = []
class Counter(metaclass=Singleton):
def __init__(self, value):
calls.append(value)
self.value = value
first = Counter(1)
second = Counter(2)
assert calls == [1], f"__init__ ran for {calls}"
assert second.value == 1
Hints (2)
Cls()runstype(Cls).__call__(Cls). In your metaclass,super().__call__(*args, **kwargs)performs the normal__new__+__init__.- Don't store the instance as a class attribute: a subclass would find its parent's instance through inheritance. Use a dictionary keyed by the class.
Show a solution
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in Singleton._instances:
Singleton._instances[cls] = super().__call__(*args, **kwargs)
return Singleton._instances[cls]Exercise 2: A plugin registry with __init_subclass__ ✓ Passed
Complete the Plugin base class so that every subclass registers itself in Plugin.registry, a dictionary mapping a name to the class:
- the name comes from a class keyword, class CsvExporter(Plugin, name='csv'); - without the keyword, use the class name in lower case; - registering a name that's already taken raises ValueError; - Plugin itself is not registered.
Use __init_subclass__, not a metaclass.
class Plugin:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
def test_explicit_name():
"""the name keyword is used as the key"""
class CsvExporter(Plugin, name='csv'):
pass
assert Plugin.registry.get('csv') is CsvExporter, f"registry: {Plugin.registry}"
def test_default_name():
"""without a keyword, the lowercased class name is used"""
class JsonExporter(Plugin):
pass
assert Plugin.registry.get('jsonexporter') is JsonExporter, f"registry: {Plugin.registry}"
def test_grandchildren():
"""subclasses of subclasses register too"""
class Base1(Plugin, name='base1'):
pass
class Derived1(Base1, name='derived1'):
pass
assert Plugin.registry.get('derived1') is Derived1
def test_duplicate():
"""a duplicate name raises ValueError"""
class First(Plugin, name='dup'):
pass
try:
class Second(Plugin, name='dup'):
pass
except ValueError:
pass
else:
raise AssertionError('expected ValueError for a duplicate name')
assert Plugin.registry['dup'] is First
def test_base_not_registered():
"""Plugin itself is not in the registry"""
assert Plugin not in Plugin.registry.values()
Hints (3)
__init_subclass__is implicitly a class method. Class keywords such asname='csv'arrive as its keyword arguments, so add aname=Noneparameter.- It runs for every subclass at any depth, but never for the class that defines it.
- Write to
Plugin.registryexplicitly so all subclasses share one dictionary.
Show a solution
class Plugin:
registry = {}
def __init_subclass__(cls, name=None, **kwargs):
super().__init_subclass__(**kwargs)
key = name or cls.__name__.lower()
if key in Plugin.registry:
raise ValueError(f'plugin name {key!r} is already registered')
Plugin.registry[key] = clsExercise 3: Catch duplicate definitions with __prepare__ ✓ Passed
Write a metaclass NoDuplicates that raises TypeError if a class body defines the same non-dunder name twice, for example two methods called area. The error message must contain the duplicated name.
Names that start with __ may be set more than once. Classes without duplicates must work normally, and the final class must have an ordinary class namespace.
Use __prepare__ to return a custom dict subclass.
class NoDuplicates(type):
pass
def test_normal_class():
"""a class without duplicates works normally"""
class Shape(metaclass=NoDuplicates):
sides = 4
def area(self):
return 1
def perimeter(self):
return 4
assert Shape().area() == 1 and Shape.sides == 4
assert type(Shape) is NoDuplicates
def test_duplicate_method():
"""two methods with the same name raise TypeError"""
try:
class Bad(metaclass=NoDuplicates):
def area(self):
return 1
def area(self):
return 2
except TypeError as ex:
assert 'area' in str(ex), f"message should mention 'area': {ex}"
else:
raise AssertionError('expected a TypeError')
def test_duplicate_attribute():
"""re-assigning a class attribute raises TypeError"""
try:
class Bad(metaclass=NoDuplicates):
color = 'red'
color = 'blue'
except TypeError:
pass
else:
raise AssertionError('expected a TypeError')
def test_dunder_allowed():
"""dunder names may be set more than once"""
class Ok(metaclass=NoDuplicates):
__doc__ = 'first'
__doc__ = 'second'
assert Ok.__doc__ == 'second'
def test_subclass():
"""subclasses use the same rule"""
class Base(metaclass=NoDuplicates):
pass
try:
class Child(Base):
x = 1
x = 2
except TypeError:
pass
else:
raise AssertionError('expected a TypeError in the subclass')
Hints (3)
- Every assignment and
defin the class body calls__setitem__on the namespace mapping. Override it in adictsubclass. - Return an instance of your mapping from
__prepare__(a@classmethodtakingmcls, name, bases, **kwargs). - In
__new__, pass a plaindict(ns)tosuper().__new__.
Show a solution
class NoDuplicatesDict(dict):
def __setitem__(self, key, value):
if key in self and not key.startswith('__'):
raise TypeError(f'{key!r} is defined more than once')
super().__setitem__(key, value)
class NoDuplicates(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
return NoDuplicatesDict()
def __new__(mcls, name, bases, ns, **kwargs):
return super().__new__(mcls, name, bases, dict(ns), **kwargs)Exercise 4: A record with attribute access ✓ Passed
Write a class Record that wraps a dictionary of fields given as keyword arguments, Record(name='Alex', age=19), and exposes them as attributes:
- reading r.name returns the field; reading an unknown field raises AttributeError; - assigning r.age = 20 updates an existing field; assigning an unknown field raises AttributeError; - r.as_dict() returns a copy of the fields; - the fields live in a single instance attribute _data (so vars(r) is {'_data': {...}}).
Use __getattr__ and __setattr__, and avoid infinite recursion by going through super() (or object) whenever you need the default behavior.
class Record:
def __init__(self, **fields):
# store the fields without triggering your own __setattr__
pass
def __getattr__(self, name):
pass
def __setattr__(self, name, value):
pass
def as_dict(self):
pass
def test_read():
"""fields can be read as attributes"""
r = Record(name='Alex', age=19)
assert (r.name, r.age) == ('Alex', 19), f"got {(r.name, r.age)}"
def test_unknown_read():
"""reading an unknown field raises AttributeError"""
r = Record(name='Alex')
try:
r.salary
except AttributeError:
pass
else:
raise AssertionError('expected AttributeError for r.salary')
assert not hasattr(r, 'salary')
def test_write():
"""assigning an existing field updates it"""
r = Record(name='Alex', age=19)
r.age = 20
assert r.age == 20 and r.as_dict() == {'name': 'Alex', 'age': 20}
def test_unknown_write():
"""assigning an unknown field raises AttributeError"""
r = Record(name='Alex')
try:
r.nickname = 'Al'
except AttributeError:
pass
else:
raise AssertionError('expected AttributeError for r.nickname = ...')
assert r.as_dict() == {'name': 'Alex'}
def test_storage():
"""fields are stored in a single _data attribute"""
r = Record(x=1, y=2)
assert vars(r) == {'_data': {'x': 1, 'y': 2}}, f"vars(r) is {vars(r)}"
def test_as_dict_is_copy():
"""as_dict returns a copy"""
r = Record(x=1)
d = r.as_dict()
d['x'] = 99
assert r.x == 1, "changing the returned dict changed the record"
Hints (3)
- In
__init__,self._data = ...would call your own__setattr__. Usesuper().__setattr__('_data', dict(fields))instead. __getattr__is only called for names the normal lookup can't find, so_dataandas_dictnever reach it.- Inside the hooks, read the dictionary with
super().__getattribute__('_data').
Show a solution
class Record:
def __init__(self, **fields):
super().__setattr__('_data', dict(fields))
def __getattr__(self, name):
data = super().__getattribute__('_data')
if name in data:
return data[name]
raise AttributeError(f'no field {name!r}')
def __setattr__(self, name, value):
data = super().__getattribute__('_data')
if name not in data:
raise AttributeError(f'no field {name!r}')
data[name] = value
def as_dict(self):
return dict(self._data)