Lazy import of module

One’s can define “lazy” module that will only load when explicitely ask. This means that we can define module that doesn’t fit our requirement and throw an error if we try to load (and haven’t installed this missing requirement). I need to try it to know if it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Inside xlsindy/__init__.py

# Import core modules here if needed

# Lazy import for the render module
def _get_render():
try:
from . import render
return render
except ImportError:
raise ImportError("The render module requires matplotlib. Install it with 'pip install xlsindy[dev]'.")

# Expose render lazily as an attribute of xlsindy
import sys
sys.modules[__name__].render = property(_get_render)

Lazy import of module
https://eymeric65.github.io/p/936fd9eef7a64fe59e77c23d10aa20a5/
Author
Eymeric Chauchat
Posted on
November 9, 2024
Licensed under