Skip to content

Improve lazy import test coverage for module level __getattr__ #149981

@sobolevn

Description

@sobolevn

There are several cases that we cover already:

That have __getattr__ functions defined on a module level.
We test that here:

  • Module:
    @support.requires_subprocess()
    def test_from_import_with_module_getattr(self):
    """Lazy from import should respect module-level __getattr__."""
    code = textwrap.dedent("""
    lazy from test.test_lazy_import.data.module_with_getattr import dynamic_attr
    assert dynamic_attr == "from_getattr"
    """)
    assert_python_ok("-c", code)
    @support.requires_subprocess()
    def test_from_import_with_imported_module_getattr(self):
    """Lazy from import should not shadow an imported module's __getattr__."""
    code = textwrap.dedent("""
    import test.test_lazy_import.data.module_with_getattr as mod
    lazy from test.test_lazy_import.data.module_with_getattr import dynamic_attr
    assert dynamic_attr == "from_getattr"
    assert mod.dynamic_attr == "from_getattr"
    """)
    assert_python_ok("-c", code)
  • Package:
    @support.requires_subprocess()
    def test_package_from_import_with_module_getattr(self):
    """Lazy from import should respect a package's __getattr__."""
    code = textwrap.dedent("""
    import test.test_lazy_import.data.pkg as pkg
    lazy from test.test_lazy_import.data.pkg import dynamic_attr
    assert dynamic_attr == "from_getattr"
    assert pkg.dynamic_attr == "from_getattr"
    """)
    assert_python_ok("-c", code)

What do we never test?

  1. Raising ImportError directly in __getattr__
  2. Calling AttributeError in __getattr__, now all names do exist and are just returned
  3. Raising some different error
  4. Raising a warning

These are all realistic cases that should be covered.
I have a PR ready.

Linked PRs

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions