Skip to content

Question: assigning the same type to all entries in a module #18813

Closed

Description

@mhvk

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?

Context: astropy/astropy#17902 - I'd prefer to avoid to add ~100KiB of stub files!

Activity

  1. A5rocks commented on Mar 18, 2025

    @A5rocks
    Collaborator

    Does module-level __getattr__ work for you?

  2. mhvk commented on Mar 19, 2025

    @mhvk
    Author

    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.

  3. hauntsaninja commented on Mar 19, 2025

    @hauntsaninja
    Collaborator

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions