.. | ||
bulkfood_v6.py | ||
bulkfood_v7.py | ||
bulkfood_v8.py | ||
model_v6.py | ||
model_v7.py | ||
model_v8.py | ||
README.md |
Legacy Class Descriptor and Metaclass Examples
Examples from Fluent Python, First Edition—Chapter 21, Class Metaprogramming, that are mentioned in Fluent Python, Second Edition—Chapter 25, Class Metaprogramming.
These examples were developed with Python 3.4. They run correctly in Python 3.9, but now it is easier to fullfill the same requirements without resorting to class decorators or metaclasses.
I have preserved them here as examples of class metaprogramming
techniques that you may find in legacy code, and that can be refactored
to simpler code using a base class with __init_subclass__
and decorators implementing __set_name__
.
Suggested Exercise
If you’d like to practice the concepts presented in chapters 24 and
25 of Fluent Python, Second Edition, you may to refactor the
most advanced example, model_v8.py
with these changes:
Simplify the
AutoStorage
descriptor by implementing__set_name__
. This will allow you to simplify theEntityMeta
metaclass as well.Rewrite the
Entity
class to use__init_subclass__
instead of theEntityMeta
metaclass—which you can then delete.
Nothing should change in the bulkfood_v8.py
code, and
its doctests should still pass.
To run the doctests while refactoring, it’s often convenient to pass
the -f
option, to exit the test runner on the first failing
test.
$ python3 -m doctest -f bulkfood_v8.py
Enjoy!