fluentpython / example-code-2e

Example code for Fluent Python, 2nd edition (O'Reilly 2022)
https://amzn.to/3J48u2J
MIT License
3.15k stars 896 forks source link

Typing for metaclass examples #42

Open jsrozner opened 4 months ago

jsrozner commented 4 months ago

Consider the example in 24-class-metaprog/factories.py (corresponds to example 24-2, page 912 in my copy)

Dog = record_factory('Dog', 'name weight owner') 
rex = Dog('Rex', 30, 'Bob')

We do not get static type checking on, e.g., rex.name

Is there an easy fix, or is this because types in metaclasses / metaprogramming are hard?

ramalho commented 4 months ago

We do not get static type checking because all effects of metaprogramming happen at runtime, and a static type checker does not run your program. It can only analyze the static source code, and it is not smart enough to understand what record_factory does, or that the string `'name weight owner' is actually naming attributes of a class that will be built at runtime.

ramalho commented 4 months ago

This is an interesting question, so I will leave the issue open until I work on chapter 24 for the third edition, hopefully in 2025.

Thanks, @jsrozner !