Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python __init_subclass__ Code

Practice configuring, validating, and registering subclasses with __init_subclass__.

Intermediate ~8 min read

Challenge 1

Add __init_subclass__ so every new subclass stores its name in Base.created.

python Your answer
class Base:
    created = []

    

class Report(Base):
    pass

print(Base.created)

Press Ctrl⌘Enter to check your answer

Challenge 2

Accept a kind keyword in the subclass header and store it on the new class.

python Your answer
class Plugin:
    def __init_subclass__(cls, /, ):
        cls.kind = kind

class CachePlugin(Plugin, kind="cache"):
    pass

print(CachePlugin.kind)

Press Ctrl⌘Enter to check your answer

Challenge 3

Forward unused subclass keywords so the next hook in the cooperative chain can receive its own option.

python Your answer
class Base:
    def __init_subclass__(cls, /, **kwargs):
        super().__init_subclass__(**kwargs)

class Configurable(Base):
    def __init_subclass__(cls, /, *, mode, **kwargs):
        
        cls.mode = mode

class Child(Configurable, mode="safe"):
    pass

print(Child.mode)

Press Ctrl⌘Enter to check your answer

Challenge 4

Reject subclasses that do not define run by raising TypeError during class creation.

python Your answer
class Command:
    def __init_subclass__(cls, /, **kwargs):
        super().__init_subclass__(**kwargs)
        

class Start(Command):
    def run(self):
        return "start"

print(Start().run())

Press Ctrl⌘Enter to check your answer