__spec__ — Advanced Playground
The module spec used to import the module
Python Playground
# Advanced __spec__ patterns
class AutoInit:
"""Automatically initialize attributes from __init__ parameters."""
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
import inspect
init = cls.__dict__.get("__init__")
if init:
params = list(inspect.signature(init).parameters.keys())[1:]
original_init = init
def new_init(self, *args, **kw):
original_init(self, *args, **kw)
cls.__init__ = new_init
class Point(AutoInit):
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(vars(p))
Output
Click "Run" to execute your code
Advanced patterns with __spec__ enable powerful metaprogramming techniques.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?