Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python Metaclasses and Class Creation Code

Practice dynamic class creation, metaclass delegation, class-namespace validation, and namespace preparation.

Advanced ~9 min read

Challenge 1

Complete the type() call to create a class called Notice with no bases and the supplied namespace.

python Your answer
Notice = type(, (), {"level": "info"})

print(Notice().level)
print(type(Notice).__name__)

Press Ctrl⌘Enter to check your answer

Challenge 2

Delegate construction of the class object to the parent metaclass.

python Your answer
class AuditMeta(type):
    def __new__(mcls, name, bases, namespace):
        print("creating", name)
        return 

class Receipt(metaclass=AuditMeta):
    pass

print(type(Receipt).__name__)

Press Ctrl⌘Enter to check your answer

Challenge 3

Finish the metaclass by creating the class after the namespace rule passes.

python Your answer
class PluginMeta(type):
    def __new__(mcls, name, bases, namespace):
        if name != "Plugin" and "plugin_name" not in namespace:
            raise TypeError("Define plugin_name")
        return 

class Plugin(metaclass=PluginMeta):
    pass

class CsvPlugin(Plugin):
    plugin_name = "csv"

print(CsvPlugin.plugin_name)

Press Ctrl⌘Enter to check your answer

Challenge 4

Return a namespace that starts with a class attribute named declared_by.

python Your answer
class NamespaceMeta(type):
    @classmethod
    def __prepare__(mcls, name, bases, **kwargs):
        return 

class Entry(metaclass=NamespaceMeta):
    value = 10

print(Entry.declared_by, Entry.value)

Press Ctrl⌘Enter to check your answer