From 2af5c6952677695c441818887b2d7e28431378fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20Gr=C3=BCter?= Date: Tue, 10 Dec 2024 13:54:38 +0100 Subject: [PATCH 1/2] Make sure that __dir__ returns a new copy of __all__ __dir__ should probably return new copies for each call so that the result will stay the same regardless of how the result of previous calls was modified. --- lazy_loader/__init__.py | 2 +- lazy_loader/tests/test_lazy_loader.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lazy_loader/__init__.py b/lazy_loader/__init__.py index deea54f..8c5ca14 100644 --- a/lazy_loader/__init__.py +++ b/lazy_loader/__init__.py @@ -90,7 +90,7 @@ def __getattr__(name): raise AttributeError(f"No {package_name} attribute {name}") def __dir__(): - return __all__ + return list(__all__) if os.environ.get("EAGER_IMPORT", ""): for attr in set(attr_to_modules.keys()) | submodules: diff --git a/lazy_loader/tests/test_lazy_loader.py b/lazy_loader/tests/test_lazy_loader.py index 42d97f8..b34a44e 100644 --- a/lazy_loader/tests/test_lazy_loader.py +++ b/lazy_loader/tests/test_lazy_loader.py @@ -104,6 +104,29 @@ def test_lazy_attach(): assert locls[k] == v +def test_lazy_attach_returns_copies(): + _get, _dir, _all = lazy.attach( + __name__, ["my_submodule", "another_submodule"], {"foo": ["some_attr"]} + ) + assert _dir() is not _dir() + assert _dir() == _all + assert _dir() is not _all + + expected = ["another_submodule", "my_submodule", "some_attr"] + assert _dir() == expected + assert _all == expected + assert _dir() is not _all + + _dir().append("modify_returned_list") + assert _dir() == expected + assert _all == expected + assert _dir() is not _all + + _all.append("modify_returned_all") + assert _dir() == expected + assert _all == expected + ["modify_returned_all"] + + def test_attach_same_module_and_attr_name(): from lazy_loader.tests import fake_pkg From df4f89a1f65e93ed90da88cac9373b1662c9a560 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20Gr=C3=BCter?= Date: Tue, 10 Dec 2024 14:21:23 +0100 Subject: [PATCH 2/2] Make linter happy --- lazy_loader/tests/test_lazy_loader.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lazy_loader/tests/test_lazy_loader.py b/lazy_loader/tests/test_lazy_loader.py index b34a44e..9fcc783 100644 --- a/lazy_loader/tests/test_lazy_loader.py +++ b/lazy_loader/tests/test_lazy_loader.py @@ -124,7 +124,7 @@ def test_lazy_attach_returns_copies(): _all.append("modify_returned_all") assert _dir() == expected - assert _all == expected + ["modify_returned_all"] + assert _all == [*expected, "modify_returned_all"] def test_attach_same_module_and_attr_name():