Skip to content

Instantly share code, notes, and snippets.

@althonos
Created May 16, 2024 16:02
Show Gist options
  • Save althonos/b3cb5a679e412d8a134f683d0ecfdf46 to your computer and use it in GitHub Desktop.
Save althonos/b3cb5a679e412d8a134f683d0ecfdf46 to your computer and use it in GitHub Desktop.
A decorator for delaying the import of a module in Python.
from imports import imports
@imports("torch.cuda")
def is_cuda_available():
return torch.cuda.is_available()
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