Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to detect lazy loaded module attributes (PEP-562) #6670

Closed
ssbarnea opened this issue Nov 15, 2024 · 1 comment
Closed

Unable to detect lazy loaded module attributes (PEP-562) #6670

ssbarnea opened this issue Nov 15, 2024 · 1 comment
Assignees
Labels
needs repro Issue has not been reproduced yet

Comments

@ssbarnea
Copy link

When using __getattr__ at module level in order to perform lazy initializations of some attributes, pylance false reports these as not being able to import. At the same time, mypy does not seem to have any problem with this.

It should be noted that use of __getattr__ at module level is documented and approved via https://peps.python.org/pep-0562/ and working since python 3.7

Environment data

  • Pylance version: v2024.11.100 (pre-release)
  • OS and version: MacOS
  • Python version (& distribution if applicable, e.g. Anaconda): 3.12

Code Snippet

To reproduce the issue, one needs to attempt to import foo from some_module, with that module having a code similar to:

#  some_module.py
from typing import Any


def __getattr__(name: str) -> Any:
    match name:
        case "foo":
            return 123
    msg = f"module {__name__!r} has no attribute {name!r}"
    raise AttributeError(msg)


__all__ = ("foo",)

Repro Steps

  1. XXX

Perform the import succesfully.

XXX

XXX

Logs

XXX
@github-actions github-actions bot added the needs repro Issue has not been reproduced yet label Nov 15, 2024
@ssbarnea ssbarnea changed the title Unable to detect lazy loaded module attributes Unable to detect lazy loaded module attributes (PEP-562) Nov 15, 2024
@rchiodo
Copy link
Contributor

rchiodo commented Nov 15, 2024

Thanks for the issue but this isn't a supported pattern for a static type checker. I presume in your real code you're doing something like this:

import importlib

def __getattr__(name):
    if name == "output"
        return importlib.import_module(".somepath.output")
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

The workaround for this situation is to have a type stub as described in this issue:
microsoft/pyright#3989

@rchiodo rchiodo closed this as completed Nov 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs repro Issue has not been reproduced yet
Projects
None yet
Development

No branches or pull requests

2 participants