Skip to content Skip to sidebar Skip to footer

How Can I Keep Imports Lightweight And Still Properly Type Annotate?

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 im

Solution 1:

Perhaps the TYPE_CHECKING constant 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

classBarClass:deflistifyme(self) -> 'List[BarClass]':
        return listify(self)

TYPE_CHECKING can also be used to avoid import cycles.

Post a Comment for "How Can I Keep Imports Lightweight And Still Properly Type Annotate?"