如何使导入保持轻量级,并且仍然正确地进行类型注释?

2024-09-29 23:14:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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']

Tags: 函数from模型importnonemodelistensorflow
1条回答
网友
1楼 · 发布于 2024-09-29 23:14:48

也许^{}常量将帮助您:

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

相关问题 更多 >

    热门问题