Created
May 16, 2024 16:02
-
-
Save althonos/b3cb5a679e412d8a134f683d0ecfdf46 to your computer and use it in GitHub Desktop.
A decorator for delaying the import of a module in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from imports import imports | |
@imports("torch.cuda") | |
def is_cuda_available(): | |
return torch.cuda.is_available() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
import importlib | |
from typing import Optional | |
from types import ModuleType | |
class imports: | |
"""A decorator for functions that require optional dependencies. | |
""" | |
module: typing.Optional["ModuleType"] | |
def __init__(self, module_name: str) -> None: | |
self.module_name = module_name | |
self.module = None | |
def __call__(self, func: "_F") -> "_F": | |
@functools.wraps(func) | |
def newfunc(*args, **kwargs): | |
if self.module is None: | |
self.module = importlib.import_module(self.module_name) | |
basename = self.module_name.split(".")[-1] | |
func.__globals__[basename] = self.module | |
return func(*args, **kwargs) | |
return newfunc # type: ignore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment