python - 如何保持导入轻量级并且仍然正确键入注释?

标签 python tensorflow mypy python-typing

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 .

关于python - 如何保持导入轻量级并且仍然正确键入注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63127784/

相关文章:

python - 为什么这个 python 脚本不起作用?

tensorflow - 如何将 .pb 转换为 TFLite 格式?

python - 如何在类型提示系统中使用通用(高级)类型变量?

python - 我应该如何使用 Keras(和 TensorFlow)编写负二项分布的损失函数?

python - 检查分配给初始设置为 None 的保护值的属性注释

python - 我的 "invalid type"错误

python - 在 pycharm 中使用标准输入

python - 使用 MultipartEncoder 从一个 Flask 路径返回多个下载

python - Discordpy2按钮interaction.edit_original_response()返回404未找到(错误代码:10015)

tensorflow - 如何使用 tensorflow .pb 文件?