Choosing a Factory Instead of a Metaclass

Your settings library now has a proxy that audits reads, a set trap that rejects bad levels, symbol keys for its protocols, and a tag that keeps audit values structured. An older Python version of this library checked levels with a metaclass, so before you combine the parts, it’s fair to ask where JavaScript keeps its metaclasses.

In this lesson, you’ll see why a proxy isn’t the answer to that question and what a plain factory function does instead.

See What a Metaclass Hooks

A metaclass runs code at the moment Python builds a class. The older library used one to check any default level a settings class defines:

Language: Python
class LevelCheck(type):
    def __new__(mcls, name, bases, namespace):
        print(f"building {name}")
        if "level" in namespace:
            level = namespace["level"]
            if type(level) is not int or not 1 <= level <= 5:
                raise ValueError(
                    f"{name}.level must be 1 to 5, not {level}"
                )
        return super().__new__(mcls, name, bases, namespace)

class DeskSettings(metaclass=LevelCheck):
    level = 2
    label = "desk"

class LabSettings(DeskSettings):
    level = 9

Both settings classes trigger the hook, and the bad one fails before a single instance exists. This shortened output omits the traceback’s file and source lines:

Language: Program Output
building DeskSettings
building LabSettings
Traceback (most recent call last):
  ...
ValueError: LabSettings.level must be 1 to 5, not 9

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.