Metaprogramming · 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 A:
    def __new__(cls):
        return 42

    def __init__(self):
        print('init')

x = A()
print(x)
2. What does type('Point', (), {'x': 0, 'y': 0}) return?
3. What does this print?
class Meta(type):
    def __new__(mcls, name, bases, ns):
        print('creating', name)
        return super().__new__(mcls, name, bases, ns)

class A(metaclass=Meta):
    pass

class B(A):
    pass

print(type(B).__name__)
4. Meta1 and Meta2 are two unrelated subclasses of type, A uses metaclass=Meta1 and B uses metaclass=Meta2. What happens with class C(A, B): pass?
5. In what order are the messages printed?
class D:
    def __set_name__(self, owner, name):
        print('set_name')

class Base:
    def __init_subclass__(cls):
        print('init_subclass')

def deco(cls):
    print('decorator')
    return cls

@deco
class C(Base):
    d = D()
6. What is the job of a metaclass's __prepare__ method?
7. What does this print?
class A:
    x = 1

    def __getattr__(self, name):
        return name.upper()

a = A()
print(a.x, a.y)
8. What happens here?
class Proxy:
    def __getattr__(self, name):
        return lambda: 3

p = Proxy()
print(p.__len__())
print(len(p))
9. What does this print?
def add_tag(cls):
    cls.tagged_by = cls.__name__
    return cls

@add_tag
class A:
    pass

class B(A):
    pass

print(B.tagged_by)
10. On Python 3.13, what does print(callable(staticmethod(f)), callable(classmethod(f))) print for an ordinary function f?
11. Which lines does this code print?
class P:
    def __init__(self):
        self.a = 1

    def __setattr__(self, name, value):
        print('set', name)
        super().__setattr__(name, value)

p = P()
p.b = 2
P.c = 3
12. What does this print?
class Meta(type):
    def __call__(cls, *args):
        if getattr(cls, '_inst', None) is None:
            cls._inst = super().__call__(*args)
        return cls._inst

class A(metaclass=Meta):
    pass

class B(A):
    pass

a = A()
b = B()
print(type(b).__name__)

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

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.

Hints (2)
  1. Cls() runs type(Cls).__call__(Cls). In your metaclass, super().__call__(*args, **kwargs) performs the normal __new__ + __init__.
  2. 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__

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.

Hints (3)
  1. __init_subclass__ is implicitly a class method. Class keywords such as name='csv' arrive as its keyword arguments, so add a name=None parameter.
  2. It runs for every subclass at any depth, but never for the class that defines it.
  3. Write to Plugin.registry explicitly 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] = cls

Exercise 3: Catch duplicate definitions with __prepare__

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.

Hints (3)
  1. Every assignment and def in the class body calls __setitem__ on the namespace mapping. Override it in a dict subclass.
  2. Return an instance of your mapping from __prepare__ (a @classmethod taking mcls, name, bases, **kwargs).
  3. In __new__, pass a plain dict(ns) to super().__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

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.

Hints (3)
  1. In __init__, self._data = ... would call your own __setattr__. Use super().__setattr__('_data', dict(fields)) instead.
  2. __getattr__ is only called for names the normal lookup can't find, so _data and as_dict never reach it.
  3. 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)