There are several cases that we cover already:
- Currently we have this module:
|
def __getattr__(name): |
|
if name == "dynamic_attr": |
|
return "from_getattr" |
|
raise AttributeError(name) |
- And this package
|
x = 42 |
|
|
|
def __getattr__(name): |
|
if name == "dynamic_attr": |
|
return "from_getattr" |
|
raise AttributeError(name) |
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?
- Raising
ImportError directly in __getattr__
- Calling
AttributeError in __getattr__, now all names do exist and are just returned
- Raising some different error
- Raising a warning
These are all realistic cases that should be covered.
I have a PR ready.
Linked PRs
There are several cases that we cover already:
cpython/Lib/test/test_lazy_import/data/module_with_getattr.py
Lines 1 to 4 in 0ed497a
cpython/Lib/test/test_lazy_import/data/pkg/__init__.py
Lines 1 to 6 in 0ed497a
That have
__getattr__functions defined on a module level.We test that here:
cpython/Lib/test/test_lazy_import/__init__.py
Lines 91 to 109 in 0ed497a
cpython/Lib/test/test_lazy_import/__init__.py
Lines 461 to 470 in 0ed497a
What do we never test?
ImportErrordirectly in__getattr__AttributeErrorin__getattr__, now all names do exist and are just returnedThese are all realistic cases that should be covered.
I have a PR ready.
Linked PRs
__getattr__#149982