![](/img/trans.png)
[英]How can I properly type annotate an expression that builds a List of Sequences?
[英]How can I keep imports lightweight and still properly type annotate?
Tensorflow是超重进口。 我只想在需要时导入它。 但是,我有一个 model 加载 function 像这样:
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 TYPE_CHECKING
中编写导入:这样它们就不会在运行时执行。
类型模块定义的TYPE_CHECKING常量在运行时为False ,但在类型检查时为True 。
例子:
# 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 也可用于避免导入循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.