Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/google/adk/a2a/agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,9 @@ def __getattr__(name: str) -> object:
except ImportError as e:
raise missing_extra("a2a-sdk", "a2a") from e
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


def __dir__() -> list[str]:
from ...utils._lazy import exported_dir

return exported_dir(globals())
6 changes: 6 additions & 0 deletions src/google/adk/apps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,9 @@ def __getattr__(name: str) -> object:
module = importlib.import_module(f'{__name__}.{_LAZY_MEMBERS[name]}')
return vars(module)[name]
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')


def __dir__() -> list[str]:
from ..utils._lazy import exported_dir

return exported_dir(globals())
6 changes: 6 additions & 0 deletions src/google/adk/artifacts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,9 @@ def __getattr__(name: str) -> object:
module = importlib.import_module(f'{__name__}.{_LAZY_MEMBERS[name]}')
return vars(module)[name]
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')


def __dir__() -> list[str]:
from ..utils._lazy import exported_dir

return exported_dir(globals())
6 changes: 6 additions & 0 deletions src/google/adk/code_executors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,9 @@ def __getattr__(name: str) -> object:
'Please install with: pip install "google-adk[extensions]"'
) from e
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")


def __dir__() -> list[str]:
from ..utils._lazy import exported_dir

return exported_dir(globals())
6 changes: 6 additions & 0 deletions src/google/adk/evaluation/simulation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@ def __getattr__(name: str) -> Any:

return LlmAudioUserSimulatorConfig
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


def __dir__() -> list[str]:
from ...utils._lazy import exported_dir

return exported_dir(globals())
6 changes: 6 additions & 0 deletions src/google/adk/memory/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,9 @@ def __getattr__(name: str) -> object:
module = importlib.import_module(f'{__name__}.{_LAZY_MEMBERS[name]}')
return vars(module)[name]
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')


def __dir__() -> list[str]:
from ..utils._lazy import exported_dir

return exported_dir(globals())
6 changes: 6 additions & 0 deletions src/google/adk/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,9 @@ def __getattr__(name: str) -> Any:
' Install with: pip install google-adk[extensions]'
) from e
return getattr(module, name)


def __dir__() -> list[str]:
from ..utils._lazy import exported_dir

return exported_dir(globals())
6 changes: 6 additions & 0 deletions src/google/adk/tools/retrieval/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,9 @@ def __getattr__(name: str) -> object:
'Please install with: pip install "google-adk[extensions]"'
) from e
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")


def __dir__() -> list[str]:
from ...utils._lazy import exported_dir

return exported_dir(globals())
21 changes: 21 additions & 0 deletions src/google/adk/utils/_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from collections.abc import Callable
from collections.abc import Mapping
import importlib
import sys
from typing import Any


Expand Down Expand Up @@ -68,3 +69,23 @@ def module_dir() -> list[str]:
return sorted(set(module_globals) | set(module_globals.get('__all__', ())))

return module_getattr, module_dir


def exported_dir(module_globals: dict[str, Any]) -> list[str]:
"""Builds a hand-written package ``__dir__``, hiding lazy exports from freezegun.

``freezegun`` calls ``getattr()`` on every name in ``dir(module)`` while
``datetime`` is patched. A lazy export listed there gets imported under
``FakeDatetime``, and ``anthropic``'s pydantic models then fail to build,
so ``freeze_time()`` raises. ``google.adk.plugins`` keeps the same guard.

Call it directly from the package's ``__dir__``: it reads the frame that
called ``dir()``.

Args:
module_globals: The calling package's ``globals()``.
"""
caller = sys._getframe(2).f_globals.get('__name__', '')
if caller == 'freezegun' or caller.startswith('freezegun.'):
return sorted(module_globals)
return sorted(set(module_globals) | set(module_globals.get('__all__', ())))
44 changes: 44 additions & 0 deletions tests/unittests/test_import_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,50 @@ def test_lazy_packages_support_star_imports():
assert result.returncode == 0, result.stderr


# Packages that resolve their exports in a hand-written __getattr__ rather than
# through _lazy.accessors, so each needs its own __dir__.
_HAND_WRITTEN_LAZY_PACKAGES = (
'google.adk.a2a.agent',
'google.adk.apps',
'google.adk.artifacts',
'google.adk.code_executors',
'google.adk.evaluation.simulation',
'google.adk.memory',
'google.adk.models',
'google.adk.tools.retrieval',
)


@pytest.mark.parametrize('module_name', _HAND_WRITTEN_LAZY_PACKAGES)
def test_hand_written_lazy_packages_list_their_exports(module_name):
"""dir() lists every export, which Sphinx autodoc needs to document it."""
result = run_isolated(f"""
import importlib

package = importlib.import_module({module_name!r})
missing = sorted(set(package.__all__) - set(dir(package)))
assert not missing, missing
""")

assert result.returncode == 0, result.stderr


@pytest.mark.parametrize('module_name', _HAND_WRITTEN_LAZY_PACKAGES)
def test_hand_written_lazy_packages_hide_exports_from_freezegun(module_name):
"""freezegun getattr()s every dir() name, so dir() must not list lazy ones."""
result = run_isolated(f"""
import importlib

package = importlib.import_module({module_name!r})
ns = {{'__name__': 'freezegun.api', 'package': package}}
exec('names = dir(package)', ns)
listed = sorted((set(package.__all__) - set(vars(package))) & set(ns['names']))
assert not listed, listed
""")

assert result.returncode == 0, result.stderr


def test_lazy_packages_resolve_subpackages_as_attributes():
"""A subpackage stays reachable on its parent, as eager imports left it."""
result = run_isolated("""
Expand Down