How can I keep imports lightweight and still properly type annotate?

家住魔仙堡 提交于 2021-02-11 06:13:12

问题


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

回答1:


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)


来源:https://stackoverflow.com/questions/63127784/how-can-i-keep-imports-lightweight-and-still-properly-type-annotate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!