如何保持导入轻量级并仍然正确键入注释?
How can I keep imports lightweight and still properly type annotate?
Tensorflow 是一个超级重磅导入。我只想在需要时导入它。但是,我有这样的模型加载功能:
from typing import Dict, Any
from keras.models import Model # Heavy import! Takes 2 seconds or so!
# Model loading is a heavy task. Only do it once and keep it in memory
model = None # type: Optional[Model]
def load_model(config: Dict[str, Any], shape) -> Model:
"""Load a model."""
if globals()['model'] is None:
globals()['model'] = create_model(wili.n_classes, shape)
print(globals()['model'].summary())
return globals()['model']
也许 TYPE_CHECKING
常量可以帮助您:
if the import is only needed for type annotations in forward references (string literals) or comments, you can write the imports inside if TYPE_CHECKING
: so that they are not executed at runtime.
The TYPE_CHECKING constant defined by the typing module is False at runtime but True while type checking.
示例:
# foo.py
from typing import List, TYPE_CHECKING
if TYPE_CHECKING:
import bar
def listify(arg: 'bar.BarClass') -> 'List[bar.BarClass]':
return [arg]
# bar.py
from typing import List
from foo import listify
class BarClass:
def listifyme(self) -> 'List[BarClass]':
return listify(self)
TYPE_CHECKING
也可以用来避免import cycles.
Tensorflow 是一个超级重磅导入。我只想在需要时导入它。但是,我有这样的模型加载功能:
from typing import Dict, Any
from keras.models import Model # Heavy import! Takes 2 seconds or so!
# Model loading is a heavy task. Only do it once and keep it in memory
model = None # type: Optional[Model]
def load_model(config: Dict[str, Any], shape) -> Model:
"""Load a model."""
if globals()['model'] is None:
globals()['model'] = create_model(wili.n_classes, shape)
print(globals()['model'].summary())
return globals()['model']
也许 TYPE_CHECKING
常量可以帮助您:
if the import is only needed for type annotations in forward references (string literals) or comments, you can write the imports inside
if TYPE_CHECKING
: so that they are not executed at runtime.
The TYPE_CHECKING constant defined by the typing module is False at runtime but True while type checking.
示例:
# foo.py
from typing import List, TYPE_CHECKING
if TYPE_CHECKING:
import bar
def listify(arg: 'bar.BarClass') -> 'List[bar.BarClass]':
return [arg]
# bar.py
from typing import List
from foo import listify
class BarClass:
def listifyme(self) -> 'List[BarClass]':
return listify(self)
TYPE_CHECKING
也可以用来避免import cycles.