如何保持导入轻量级并且仍然正确键入注释? [英] How can I keep imports lightweight and still properly type annotate?

查看:38
本文介绍了如何保持导入轻量级并且仍然正确键入注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Tensorflow 是一个超重的导入.我只想在需要时导入它.但是,我有这样的模型加载功能:

from typing import Dict, Anyfrom keras.models import Model # 重磅导入!需要2秒左右!# 模型加载是一项繁重的任务.只做一次并保存在内存中模型 = 无 # 类型:可选[模型]def load_model(config: Dict[str, Any], shape) ->模型:"加载模型.""如果 globals()['model'] 是 None:globals()['model'] = create_model(wili.n_classes, shape)打印(全局变量()['模型'].summary())返回全局变量()['模型']

解决方案

也许是变量 TYPE_CHECKING 会帮助你:

<块引用>

如果仅在前向引用(字符串文字)或注释中的类型注释需要导入,您可以将导入写入 if TYPE_CHECKING: 以便它们不会在运行时执行.

<块引用>

打字模块定义的 TYPE_CHECKING 常量在运行时为 False,但在类型检查时为 True.

示例:

# foo.py从输入导入列表,TYPE_CHECKING如果 TYPE_CHECKING:进口酒吧def listify(arg: 'bar.BarClass') ->'列表[bar.BarClass]':返回 [参数]

# bar.py从键入导入列表从 foo 导入 listify类 BarClass:def listifyme(self) ->'列表[BarClass]':返回 listify(self)

TYPE_CHECKING 还可用于避免导入周期.

Tensorflow is a super heavy import. I want to import it only when it's needed. However, I have a model loading function like this:

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

解决方案

Perhaps variable TYPE_CHECKING will help you:

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.

Example:

# 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 can also be used to avoid import cycles.

这篇关于如何保持导入轻量级并且仍然正确键入注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆