Skip to content

Commit 10f8ba2

Browse files
lazy import support
1 parent 97564bc commit 10f8ba2

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@
5757

5858
- Generalize `scatter` method for backends.
5959

60+
- Lazy import for tensorflow and torch.
61+
6062

6163
## v1.4.0
6264

tensorcircuit/__init__.py

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
__author__ = "TensorCircuit-NG Authors"
33
__creator__ = "refraction-ray"
44

5+
import importlib
6+
from typing import Any, List
57
from .utils import gpu_memory_share
68

79
gpu_memory_share()
@@ -62,17 +64,34 @@
6264

6365
FGSCircuit = FGSSimulator
6466

65-
try:
66-
from . import keras
67-
from .keras import KerasLayer, KerasHardwareLayer
68-
except ModuleNotFoundError:
69-
pass # in case tf is not installed
67+
# lazy imports for heavy frameworks
68+
# name: (module_relative_path, is_module)
69+
_lazy_imports = {
70+
"keras": (".keras", True),
71+
"KerasLayer": (".keras", False),
72+
"KerasHardwareLayer": (".keras", False),
73+
"torchnn": (".torchnn", True),
74+
"TorchLayer": (".torchnn", False),
75+
"TorchHardwareLayer": (".torchnn", False),
76+
}
77+
78+
79+
def __getattr__(name: str) -> Any:
80+
if name in _lazy_imports:
81+
path, is_module = _lazy_imports[name]
82+
module = importlib.import_module(path, __package__)
83+
if is_module:
84+
attr = module
85+
else:
86+
attr = getattr(module, name)
87+
globals()[name] = attr
88+
return attr
89+
raise AttributeError("module %s has no attribute %s" % (__name__, name))
90+
91+
92+
def __dir__() -> List[str]:
93+
return sorted(set(globals().keys()).union(_lazy_imports.keys()))
7094

71-
try:
72-
from . import torchnn
73-
from .torchnn import TorchLayer, TorchHardwareLayer
74-
except ModuleNotFoundError:
75-
pass # in case torch is not installed
7695

7796
try:
7897
import qiskit

0 commit comments

Comments
 (0)