Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 35 / ADVANCED LANGUAGE FEATURES

Class hooks and metaclasses without mystery

Know the mechanism and recognise when a simpler design wins.

AdvancedTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain classes are objects too
  • Apply use a subclass hook for registration
  • Reason about avoid invisible application control flow
01

Classes are objects too

A Python class is itself an object. type normally creates that class object before any instance of the class is constructed.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Understand the creation stages before reaching for a metaclass. Most customization can be handled by an ordinary factory, decorator or subclass hook.

Words you will see

Class object
The object that describes a class and is called to create its instances.
Instance
An object made from a class.
Metaclass
The class responsible for creating class objects; normally type.

Separate class creation from instance creation

The class statement executes a body to collect attributes, then creates the Tool class object. Tool() later creates an instance. type(Tool) is type, while type(item) is Tool.

The same type tool can inspect an object or build a class from a name, bases and attribute namespace. That lower-level construction is useful to understand, but it is usually less readable than an ordinary class statement.

Use the smallest creation boundary

If all you need is to configure one instance, use __init__ or a factory. A class decorator can validate a finished class; __init_subclass__ can react when a subclass is made.

A metaclass can alter the class-creation protocol itself, which brings more responsibilities and potential conflicts with frameworks. Do not introduce it merely to avoid writing an explicit registration call.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. class Tool:

    Execute a class definition to create a class object.

  2. item = Tool()

    Call the class to construct an instance.

  3. print(type(Tool) is type)

    Inspect the creator category of the class object.

  4. print(type(item) is Tool)

    Inspect the instance's own class.

A class is created by a metaclass, normally type. A metaclass can customise class creation, but most application tasks do not require one. A class decorator or __init_subclass__ often provides a smaller extension point.

Conceptual cause and effect, not a live runtime trace

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Execute bodyCollect Tool's declared attributes.
  2. Create classtype builds the Tool class object.
  3. Create instanceTool() constructs item later; class hooks are not per-instance initialization.
Predict before you run

Is type(item) the built-in type here?

Distinguish class and instancePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Create another instance.

Try: Add other = Tool() and print(item is other).

It prints False; the instances are separate despite sharing one class.

Change a class attribute.

Try: Set Tool.label = 'waiting' before the final print.

item.label reads waiting because the instance has no overriding label and lookup reaches the class.

Before you move on

A class is defined once and instantiated five times. How many class objects and instances does this create?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

One class object and five instances, assuming this ordinary class definition and no custom construction behavior.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Use a subclass hook for registration

__init_subclass__ runs when a new subclass is created, letting a base validate or register the subclass without a custom metaclass.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use a subclass hook for a narrow inherited rule, such as requiring a label. Keep side effects scoped and explain when they occur.

Words you will see

Subclass
A class that inherits behavior from another class.
Class keyword
A keyword in a class header passed through the class-creation protocol.
Cooperative hook
A hook that forwards unconsumed options to super so other bases can participate.

Run at definition, not at construction

When Loud is defined, Python calls Named's hook with cls equal to Loud and label equal to 'loud'. The hook forwards remaining keywords, then assigns label on the new subclass.

No Loud instance exists yet. The final print reads Loud.label directly from the class. A required keyword causes a missing-label class definition to fail early instead of deferring an unclear error until use.

Cooperate rather than swallow options

Use **kwargs and super().__init_subclass__(**kwargs) when supporting cooperative multiple inheritance. Consume only the options your hook owns. Unknown options should not be silently ignored.

Explicit registration after a class definition is still simpler when inheritance is not part of the domain. A decorator can add one label without making every future descendant participate in the hook contract.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def __init_subclass__(cls, *, label, **kwargs):

    Receive the newly created subclass and required class keyword.

  2. super().__init_subclass__(**kwargs)

    Forward only options not owned by this hook.

  3. cls.label = label

    Store this class's configured label.

  4. print(Loud.label)

    Observe the completed class configuration without constructing an instance.

__init_subclass__ is called when a subclass is created. Keep registrations explicit, scoped and reversible where tests or plugin reloads need isolation. Avoid turning import order into a hidden dependency.

Predict before you run

What happens if label='loud' is omitted from this class header?

Require a declared labelPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Change the label.

Try: Use label='quiet' in the subclass header.

The hook stores quiet and the print changes accordingly.

Add a second subclass.

Try: Define Soft(Named, label='soft') and print both labels.

Loud stays loud while Soft has soft; each assignment targets its own cls.

Before you move on

A hook appends each new subclass name to a local registry. Does creating three instances of one subclass add three names?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. The subclass definition triggers one registration. Instance construction is a different stage.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Register a declared handler

A subclass registry connects an explicit key to the subclass declared under it. A hook can maintain that registry at class-definition time.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use this mechanism for a small set of declared handlers, but specify duplicate behavior and ownership before using it as a plugin system.

Words you will see

Registry
A mapping from explicit lookup keys to known classes or functions.
Registration
Adding a declared object under its lookup key.
Duplicate policy
The chosen behavior when a key is registered more than once.

Follow the declared handler

Handler starts with an empty registry shared through that base. Defining JsonHandler calls the base hook with name='json'. The assignment stores the newly created JsonHandler class under that key.

The final lookup reads the class object, then its __name__ string. It does not construct an instance and does not parse JSON. This snippet's assignment would replace an earlier entry with the same key.

Scope and validate real registries

For a production registry, choose whether duplicates reject, replace or require an explicit override. A factory-owned base and registry are easier to isolate in tests than a process-global mapping.

Defining classes during import can affect registry state and make import order visible. Prefer explicit registration if load order would otherwise control business behavior. Do not imply this hook discovers or trusts arbitrary external plugins.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. registry = {}

    Create the shared base registry.

  2. Handler.registry[name] = cls

    Store the newly declared subclass under the provided key.

  3. class JsonHandler(Handler, name='json'):

    Trigger the hook once while defining this subclass.

  4. print(Handler.registry['json'].__name__)

    Read the class object's own name, not an instance.

A built-in class-creation hook handles the registration without introducing a custom metaclass. A production registry also needs a deliberate duplicate-name policy.

Predict before you run

Does the final line instantiate JsonHandler?

Register a declared handlerPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Register another key.

Try: Define TextHandler(Handler, name='text') and print(sorted(Handler.registry)).

The keys are ['json', 'text']; sorting is a display choice.

Expose replacement.

Try: Define OtherHandler(Handler, name='json') before the print.

The print becomes OtherHandler because the original hook allows replacement.

Before you move on

With this exact hook, a second subclass is declared with name='json'. Which class remains under that key?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

The second one. Ordinary dictionary assignment replaces the existing entry. A reject-on-duplicate policy needs an explicit check before assignment.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Class-creation hooks are useful for framework-level policies such as registration or validating declarations. They are rarely the first tool an application needs. A class decorator, factory or explicit registry is usually easier to inspect when the requirement does not actually concern how classes themselves are constructed.

Follow the mechanism step by step

A class is an object created through a metaclass, normally type. __init_subclass__ provides a smaller hook invoked when a subclass is created. The registration example receives a declared name and stores the new class. That work happens during class definition, often while importing the module, not when constructing each instance.

Work through a concrete application

Define the registry's ownership and duplicate-name policy before implementing automatic registration. Trace what occurs when two subclasses request the same name. Decide whether registration may be undone for tests or plugins. Prefer explicit startup discovery when implicit import order would otherwise control which features exist.

Failure cases and misleading shortcuts

Metaclass conflicts can occur when combining bases with incompatible class-creation requirements. A hook that silently rewrites methods or performs I/O makes debugging harder. Do not implement magic merely to avoid writing a visible registration call, and do not treat a class definition as a safe place for unrestricted side effects.

Cost, ownership and alternatives

The maintenance cost is largely cognitive: future readers need to know both ordinary inheritance and the creation policy. Runtime introspection and dynamic code generation can also complicate static analysis. A simple factory or composition may provide the same extensibility with fewer hidden interactions.

Verify the contract

Test declaration errors at class-creation time, duplicate registration, inheritance behaviour and registry isolation. Confirm the resulting class still satisfies its public contract. If a custom metaclass is truly required, document how it composes with existing framework bases and test that combination rather than only one standalone example.

Transfer question: When would a class decorator be preferable to a metaclass?

When the transformation can occur after an ordinary class has been created and does not need to control the construction protocol. It is an explicit opt-in applied at the definition and can avoid metaclass conflicts while keeping the policy visible.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

What is a sensible first option for simple subclass registration?
TRANSFER THE IDEA

Rebuild: Register a declared handler

Without copying the worked code, reproduce its observable contract: A built-in class-creation hook handles the registration without introducing a custom metaclass. A production registry also needs a deliberate duplicate-name policy. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Build an isolated duplicate-safe registry

Return a fresh base class and its registry; subclasses declare their registration key with name=.

The contract

  • No input. Return (Base, registry), an actual tuple with a class and an initially empty dict.
  • Defining a subclass with a new string name registers that exact class; duplicate names raise ValueError without replacing the first entry.
  • Each call owns its registry. Base.registry is that registry. Registration occurs on class definition, not instance construction; no global mapping.
Build an isolated duplicate-safe registryPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. Registry ownership 1
    pair = registry_base()
    assert type(pair) is tuple and len(pair) == 2
    Base, registry = pair
    assert isinstance(Base, type) and type(registry) is dict and registry == {} and Base.registry is registry
    class First(Base, name="json"):
        pass
    assert registry == {"json": First} and registry["json"] is First
    try:
        class Duplicate(Base, name="json"):
            pass
    except ValueError:
        pass
    else:
        raise AssertionError('duplicate accepted')
    First()
    assert registry == {"json": First}
    Other, separate = registry_base()
    assert type(separate) is dict and separate == {} and separate is not registry and Other is not Base and Other.registry is separate
  2. Registry ownership 2
    pair = registry_base()
    assert type(pair) is tuple and len(pair) == 2
    Base, registry = pair
    assert isinstance(Base, type) and type(registry) is dict and registry == {} and Base.registry is registry
    class First(Base, name=""):
        pass
    assert registry == {"": First} and registry[""] is First
    try:
        class Duplicate(Base, name=""):
            pass
    except ValueError:
        pass
    else:
        raise AssertionError('duplicate accepted')
    First()
    assert registry == {"": First}
    Other, separate = registry_base()
    assert type(separate) is dict and separate == {} and separate is not registry and Other is not Base and Other.registry is separate
  3. Registry ownership 3
    pair = registry_base()
    assert type(pair) is tuple and len(pair) == 2
    Base, registry = pair
    assert isinstance(Base, type) and type(registry) is dict and registry == {} and Base.registry is registry
    class First(Base, name="same"):
        pass
    assert registry == {"same": First} and registry["same"] is First
    try:
        class Duplicate(Base, name="same"):
            pass
    except ValueError:
        pass
    else:
        raise AssertionError('duplicate accepted')
    First()
    assert registry == {"same": First}
    Other, separate = registry_base()
    assert type(separate) is dict and separate == {} and separate is not registry and Other is not Base and Other.registry is separate
  4. Registry ownership 4
    pair = registry_base()
    assert type(pair) is tuple and len(pair) == 2
    Base, registry = pair
    assert isinstance(Base, type) and type(registry) is dict and registry == {} and Base.registry is registry
    class First(Base, name="x"):
        pass
    assert registry == {"x": First} and registry["x"] is First
    try:
        class Duplicate(Base, name="x"):
            pass
    except ValueError:
        pass
    else:
        raise AssertionError('duplicate accepted')
    First()
    assert registry == {"x": First}
    Other, separate = registry_base()
    assert type(separate) is dict and separate == {} and separate is not registry and Other is not Base and Other.registry is separate
  5. Registry ownership 5
    pair = registry_base()
    assert type(pair) is tuple and len(pair) == 2
    Base, registry = pair
    assert isinstance(Base, type) and type(registry) is dict and registry == {} and Base.registry is registry
    class First(Base, name="worker"):
        pass
    assert registry == {"worker": First} and registry["worker"] is First
    try:
        class Duplicate(Base, name="worker"):
            pass
    except ValueError:
        pass
    else:
        raise AssertionError('duplicate accepted')
    First()
    assert registry == {"worker": First}
    Other, separate = registry_base()
    assert type(separate) is dict and separate == {} and separate is not registry and Other is not Base and Other.registry is separate
  6. Registry ownership 6
    pair = registry_base()
    assert type(pair) is tuple and len(pair) == 2
    Base, registry = pair
    assert isinstance(Base, type) and type(registry) is dict and registry == {} and Base.registry is registry
    class First(Base, name="report"):
        pass
    assert registry == {"report": First} and registry["report"] is First
    try:
        class Duplicate(Base, name="report"):
            pass
    except ValueError:
        pass
    else:
        raise AssertionError('duplicate accepted')
    First()
    assert registry == {"report": First}
    Other, separate = registry_base()
    assert type(separate) is dict and separate == {} and separate is not registry and Other is not Base and Other.registry is separate
    Why close over a registry instead of assigning through cls.registry?

    A subclass could shadow cls.registry. Closing over the factory-owned mapping makes the intended owner explicit. Expected insertion work is constant per name under ordinary dictionary behavior; stored classes retain space proportional to registrations.

    GUIDED PRACTICE

    Let a descriptor learn its declared name

    Build a field descriptor whose ordinary class access returns itself and instance access returns its learned attribute name.

    The contract

    • No input. Return a fresh descriptor object implementing __set_name__ and __get__.
    • One field object is assigned to exactly one attribute of one class. __set_name__ records that class in owner and the attribute string in name.
    • Instance access returns the name as a str without writing to the instance. Class access returns the exact field. Distinct factory calls must not share descriptor state.
    Let a descriptor learn its declared namePYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. Descriptor binding 1
      field = named_field()
      other = named_field()
      assert field is not None and field is not other and callable(getattr(field, '__set_name__', None)) and callable(getattr(field, '__get__', None))
      class Model:
          price = field
      instance = Model()
      before = dict(instance.__dict__)
      result = instance.price
      assert type(result) is str and result == "price"
      assert Model.price is field and field.owner is Model and field.name == "price" and instance.__dict__ == before
      class Other:
          alternate = other
      assert Other.alternate is other and Other().alternate == 'alternate' and field.owner is Model and field.name == "price"
    2. Descriptor binding 2
      field = named_field()
      other = named_field()
      assert field is not None and field is not other and callable(getattr(field, '__set_name__', None)) and callable(getattr(field, '__get__', None))
      class Model:
          code = field
      instance = Model()
      before = dict(instance.__dict__)
      result = instance.code
      assert type(result) is str and result == "code"
      assert Model.code is field and field.owner is Model and field.name == "code" and instance.__dict__ == before
      class Other:
          alternate = other
      assert Other.alternate is other and Other().alternate == 'alternate' and field.owner is Model and field.name == "code"
    3. Descriptor binding 3
      field = named_field()
      other = named_field()
      assert field is not None and field is not other and callable(getattr(field, '__set_name__', None)) and callable(getattr(field, '__get__', None))
      class Model:
          label = field
      instance = Model()
      before = dict(instance.__dict__)
      result = instance.label
      assert type(result) is str and result == "label"
      assert Model.label is field and field.owner is Model and field.name == "label" and instance.__dict__ == before
      class Other:
          alternate = other
      assert Other.alternate is other and Other().alternate == 'alternate' and field.owner is Model and field.name == "label"
    4. Descriptor binding 4
      field = named_field()
      other = named_field()
      assert field is not None and field is not other and callable(getattr(field, '__set_name__', None)) and callable(getattr(field, '__get__', None))
      class Model:
          x = field
      instance = Model()
      before = dict(instance.__dict__)
      result = instance.x
      assert type(result) is str and result == "x"
      assert Model.x is field and field.owner is Model and field.name == "x" and instance.__dict__ == before
      class Other:
          alternate = other
      assert Other.alternate is other and Other().alternate == 'alternate' and field.owner is Model and field.name == "x"
    5. Descriptor binding 5
      field = named_field()
      other = named_field()
      assert field is not None and field is not other and callable(getattr(field, '__set_name__', None)) and callable(getattr(field, '__get__', None))
      class Model:
          total = field
      instance = Model()
      before = dict(instance.__dict__)
      result = instance.total
      assert type(result) is str and result == "total"
      assert Model.total is field and field.owner is Model and field.name == "total" and instance.__dict__ == before
      class Other:
          alternate = other
      assert Other.alternate is other and Other().alternate == 'alternate' and field.owner is Model and field.name == "total"
    6. Descriptor binding 6
      field = named_field()
      other = named_field()
      assert field is not None and field is not other and callable(getattr(field, '__set_name__', None)) and callable(getattr(field, '__get__', None))
      class Model:
          field_2 = field
      instance = Model()
      before = dict(instance.__dict__)
      result = instance.field_2
      assert type(result) is str and result == "field_2"
      assert Model.field_2 is field and field.owner is Model and field.name == "field_2" and instance.__dict__ == before
      class Other:
          alternate = other
      assert Other.alternate is other and Other().alternate == 'alternate' and field.owner is Model and field.name == "field_2"
      Why not save the name in one class variable on Field?

      Different descriptor instances would overwrite each other's state. This design stores owner and name on each field instance, using constant extra state per field and no instance mutation.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: opt-in class validation

      Requirements changed: validate an existing class explicitly rather than inheriting a hook or creating a descriptor.

      The contract

      • Accept a class object. Its key must be declared in that class's own __dict__, not merely inherited.
      • key must be a nonempty str; return the exact class on success. Whitespace-only strings are nonempty and accepted.
      • Otherwise raise ValueError. Never mutate the class or any base, and do not instantiate the class to inspect it.
      Transfer: opt-in class validationPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. Explicit validation 1
        class Parent:
            key = 'inherited'
        class Candidate(Parent):
            key = 'json'
        before = dict(Candidate.__dict__)
        parent_before = dict(Parent.__dict__)
        result = require_own_key(Candidate)
        assert isinstance(result, type) and result is Candidate
        assert dict(Candidate.__dict__) == before and dict(Parent.__dict__) == parent_before
      2. Explicit validation 2
        class Parent:
            key = 'inherited'
        class Candidate(Parent):
            key = ' '
        before = dict(Candidate.__dict__)
        parent_before = dict(Parent.__dict__)
        result = require_own_key(Candidate)
        assert isinstance(result, type) and result is Candidate
        assert dict(Candidate.__dict__) == before and dict(Parent.__dict__) == parent_before
      3. Explicit validation 3
        class Parent:
            key = 'inherited'
        class Candidate(Parent):
            key = ''
        before = dict(Candidate.__dict__)
        parent_before = dict(Parent.__dict__)
        try:
            result = require_own_key(Candidate)
        except ValueError:
            pass
        else:
            raise AssertionError('invalid declaration accepted')
        assert dict(Candidate.__dict__) == before and dict(Parent.__dict__) == parent_before
      4. Explicit validation 4
        class Parent:
            key = 'inherited'
        class Candidate(Parent):
            key = 7
        before = dict(Candidate.__dict__)
        parent_before = dict(Parent.__dict__)
        try:
            result = require_own_key(Candidate)
        except ValueError:
            pass
        else:
            raise AssertionError('invalid declaration accepted')
        assert dict(Candidate.__dict__) == before and dict(Parent.__dict__) == parent_before
      5. Explicit validation 5
        class Parent:
            key = 'inherited'
        class Candidate(Parent):
            pass
        before = dict(Candidate.__dict__)
        parent_before = dict(Parent.__dict__)
        try:
            result = require_own_key(Candidate)
        except ValueError:
            pass
        else:
            raise AssertionError('invalid declaration accepted')
        assert dict(Candidate.__dict__) == before and dict(Parent.__dict__) == parent_before
      6. Explicit validation 6
        class Parent:
            key = 'inherited'
        class Candidate(Parent):
            key = None
        before = dict(Candidate.__dict__)
        parent_before = dict(Parent.__dict__)
        try:
            result = require_own_key(Candidate)
        except ValueError:
            pass
        else:
            raise AssertionError('invalid declaration accepted')
        assert dict(Candidate.__dict__) == before and dict(Parent.__dict__) == parent_before
        Why is an inherited key insufficient?

        The changed contract requires every class to opt in with its own declaration. getattr would silently accept the parent's key. Inspection and validation use constant auxiliary state for this fixed field, without global registration or instance construction.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Metaclass conflicts are design feedback

        A metaclass conflict occurs when Python cannot choose one compatible creator for the requested base classes.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Treat conflicts as feedback about framework composition rather than patching bases until a class statement happens to succeed.

        Words you will see

        Base class
        A parent whose behavior a class inherits.
        Compatible metaclass
        A creator satisfying the metaclass requirements of all bases.
        Composition
        Using one object through another instead of inheriting all of its class-creation rules.

        Two unrelated creators disagree

        Left is created by LeftMeta and Right by RightMeta. Neither metaclass is a subclass of the other, so class Both(Left, Right) has no automatic compatible creator. TypeError occurs at class creation, before any Both instance.

        The try block intentionally catches that error and prints a stable label, not a version-dependent exception message. The example does not need external frameworks to expose the mechanism.

        A combined metaclass is not a universal repair

        A carefully designed metaclass inheriting both creators may satisfy the formal compatibility rule, but both protocols must also cooperate semantically. Conflicting namespace preparation, transformations or required options can still be wrong.

        Prefer composition or a shared interface when mixing framework inheritance is unnecessary. A class decorator works on a completed class and avoids taking over creation; use it for narrow validation that does not require the broader protocol.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. class LeftMeta(type):

          Declare one class creator.

        2. class RightMeta(type):

          Declare a separate, unrelated creator.

        3. class Both(Left, Right):

          Ask Python to combine bases with incompatible creators.

        4. print('incompatible creators')

          Handle the class-definition failure without depending on its exact message.

        Multiple bases with incompatible metaclasses can prevent class creation. Combining framework hierarchies may carry contracts beyond their method names. Understand who owns class creation before composing them.

        Predict before you run

        Does the failure wait until Both()?

        Observe incompatible creatorsPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Use one base.

        Try: Change class Both(Left, Right) to class Both(Left).

        No conflict occurs, so the handled-error print disappears.

        Make creators related.

        Try: Change RightMeta(type) to RightMeta(LeftMeta).

        RightMeta is now a compatible more-derived creator for these simple empty protocols; the error print disappears.

        Before you move on

        If a wrapper object can delegate to Left and Right separately, must it inherit both and combine their metaclasses?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. Composition can use both collaborators without making one class inherit their creation protocols.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Avoid invisible application control flow

        A class decorator receives a completed class and can validate or annotate it explicitly, without owning the whole metaclass protocol.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Prefer a narrow, visible transformation when the requirement is just checking one field or adding metadata.

        Words you will see

        Class decorator
        A callable applied to a completed class, whose return value becomes the class binding.
        Validation
        Checking a promised property and rejecting invalid input clearly.
        Descriptor hook
        A field object's __set_name__ method, notified of its owning class and attribute name during ordinary class creation.

        Keep the transformation readable

        require_label checks the completed class's label. If it is absent or not a string, the decorator raises TypeError. Otherwise it returns the same class, so normal instance construction still uses that class.

        The @require_label line is equivalent in purpose to applying the function to the newly built class before binding the final name. A decorator that returns None would replace the class name with None, breaking later calls.

        Match the hook to the requirement

        Use a descriptor's __set_name__ when a field needs to learn its own declared name. Use __init_subclass__ for an inherited rule. Use a decorator when validation should be opt-in and explicit at a definition.

        Avoid hidden I/O, broad method rewriting and process-global side effects in all these mechanisms. A metaclass is justified only when the actual class-creation protocol needs control, not because it is the most powerful available hook.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. def require_label(cls):

          Receive the completed class as an ordinary function argument.

        2. return cls

          Preserve the class instead of accidentally replacing it with None.

        3. @require_label

          Apply the narrow validation at the class definition.

        4. print(Ready().label)

          Construct an ordinary instance only after validation succeeds.

        A metaclass that silently rewrites methods or performs I/O makes debugging difficult. Prefer ordinary factories, composition, dataclasses or explicit registration until the class-creation requirement genuinely needs a metaclass.

        Predict before you run

        What if label = 5 replaces the string?

        Validate a completed classPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Use another valid label.

        Try: Set label = 'waiting'.

        The first output becomes waiting, while the class name remains Ready.

        Demonstrate the return requirement.

        Try: Replace return cls with return None.

        The class binding becomes None, so Ready() raises TypeError rather than constructing an instance.

        Before you move on

        A field object needs to know that it was assigned as price on a class. Is a process-global registry or metaclass necessary?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Usually not. Its __set_name__(owner, name) hook receives that name during normal class creation. This is a smaller, field-specific extension point.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.