A metaclass in Python
The class of a class: it runs at definition time and can rewrite the class.
class Uppercase(type):
def __new__(mcls, name, bases, namespace):
constants = {k: v for k, v in namespace.items()
if k.isupper() and isinstance(v, str)}
for key, value in constants.items():
namespace[key] = value.upper()
namespace["CONSTANTS"] = tuple(sorted(constants))
return super().__new__(mcls, name, bases, namespace)
class Config(metaclass=Uppercase):
THEME = "monokai"
MODE = "editor"
other = "left alone"
print(Config.THEME, Config.MODE, Config.other)
print(Config.CONSTANTS, type(Config).__name__)
How it works
__new__on the metaclass receives the namespace being built.- Reach for it only when
__init_subclass__cannot do the job. type(cls)tells you which metaclass made a class.
Keywords and builtins used here
ConfigUppercaseclassdefforifisinstanceprintreturnsortedstrsupertupletype
The run, in numbers
- Lines
- 18
- Characters to type
- 511
- Tokens
- 148
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 81 seconds.
Step 3 of 3 in Class machinery, step 37 of 53 in Pythonic Python.