example-code-2e/24-class-metaprog/bulkfood/README.md
2021-09-10 12:34:39 -03:00

1.4 KiB
Raw Blame History

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 youd 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:

  1. Simplify the AutoStorage descriptor by implementing __set_name__. This will allow you to simplify the EntityMeta metaclass as well.

  2. Rewrite the Entity class to use __init_subclass__ instead of the EntityMeta 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, its 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!