Skip to content

Commit 52efb98

Browse files
sararobcopybara-github
authored andcommitted
fix: Enable from vertexai.types import TypeName without needing to run from vertexai import types first
PiperOrigin-RevId: 834811652
1 parent 9304f15 commit 52efb98

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

tests/unit/architecture/test_vertexai_import.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,9 @@ def test_vertexai_import():
8181
new_modules_after_vertexai = modules_after_vertexai - modules_before_vertexai
8282

8383
vertexai_module_name = vertexai.__name__ # == "vertexai"
84-
assert sorted(new_modules_after_vertexai) == [vertexai_module_name]
84+
assert sorted(new_modules_after_vertexai) == [
85+
vertexai_module_name + "google.cloud.aiplatform.vertexai.types"
86+
]
8587

8688
assert vertexai_import_timedelta.total_seconds() < 0.005
8789
assert aip_import_timedelta.total_seconds() < 40

vertexai/__init__.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
import importlib
1818
import sys
1919

20+
from types import ModuleType
21+
2022
from google.cloud.aiplatform import version as aiplatform_version
2123

2224
__version__ = aiplatform_version.__version__
@@ -27,6 +29,22 @@
2729
_genai_types = None
2830

2931

32+
class _LazyTypesLoader(ModuleType):
33+
"""A module that lazily loads the types module when an attribute is accessed via from `vertexai.types import TypeName`."""
34+
35+
def __init__(self, *args, **kwargs):
36+
super().__init__(*args, **kwargs)
37+
self._module = None
38+
39+
def __getattr__(self, name):
40+
if self._module is None:
41+
self._module = importlib.import_module("._genai.types", __package__)
42+
return getattr(self._module, name)
43+
44+
# Register a placeholder _LazyTypesLoader instance for vertexai.types until it is accessed.
45+
sys.modules[__name__ + ".types"] = _LazyTypesLoader(__name__ + ".types")
46+
47+
3048
def __getattr__(name): # type: ignore[no-untyped-def]
3149
# Lazy importing the preview submodule
3250
# See https://peps.python.org/pep-0562/
@@ -45,12 +63,7 @@ def __getattr__(name): # type: ignore[no-untyped-def]
4563
return getattr(_genai_client, name)
4664

4765
if name == "types":
48-
global _genai_types
49-
if _genai_types is None:
50-
_genai_types = importlib.import_module("._genai.types", __name__)
51-
if "vertexai.types" not in sys.modules:
52-
sys.modules["vertexai.types"] = _genai_types
53-
return _genai_types
66+
return sys.modules[__name__ + ".types"]
5467

5568
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
5669

0 commit comments

Comments
 (0)