You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Question: assigning the same type to all entries in a module #18813
Is it possible to let mypy infer programmatically that all members of a given module have the same type? We run into this problem in astropy for definitions of units; in our code, prefixed versions are generated automatically, so it is less obvious how to infer the type, and the fall-back we are considering is automatically generated stub files. But I wonder if one cannot be smarter. E.g., I think if the units were in a dict[str, Unit], it would work, but is there a way to let mypy know that everything in a given module has type Unit by default?
Interesting, I hadn't really thought about how not defining the units but creating them on demand with __getattr__ which is clearly annotated to produce only units might do the trick. It might actually be handy overall in our implementation (see astropy/astropy#17902 (comment)). But I partially wrote this issue because I'm not super familiar with typing yet am reviewing a PR that would add ~100KiB worth of stubs, and am trying to think of ways to avoid that -- so I'm asking our more typing-versed people over at that issue.
You can lie in the stub and have a __getattr__ in the .pyi file even if that's not the strategy you take to creating attributes at runtime in the .py file
Activity
A5rocks commentedon Mar 18, 2025
Does module-level
__getattr__work for you?mhvk commentedon Mar 19, 2025
Interesting, I hadn't really thought about how not defining the units but creating them on demand with
__getattr__which is clearly annotated to produce only units might do the trick. It might actually be handy overall in our implementation (see astropy/astropy#17902 (comment)). But I partially wrote this issue because I'm not super familiar with typing yet am reviewing a PR that would add ~100KiB worth of stubs, and am trying to think of ways to avoid that -- so I'm asking our more typing-versed people over at that issue.hauntsaninja commentedon Mar 19, 2025
You can lie in the stub and have a
__getattr__in the.pyifile even if that's not the strategy you take to creating attributes at runtime in the.pyfile