Skip to content

Commit

Permalink
ENH: Delay loading of less likely modules
Browse files Browse the repository at this point in the history
Using python -X importtime -c "import lazy_loader":

Before
------
import time: self [us] | cumulative | imported package
[...]
import time:       131 |      22995 | lazy_loader

After
-----
import time: self [us] | cumulative | imported package
[...]
import time:       115 |       4248 | lazy_loader
  • Loading branch information
effigies committed Mar 25, 2023
1 parent 67dc396 commit 10dffc6
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions lazy_loader/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,10 @@
import ast
import importlib
import importlib.util
import inspect
import os
import sys
import types

try:
import importlib_metadata
except ImportError:
import importlib.metadata as importlib_metadata

__all__ = ["attach", "load", "attach_stub"]


Expand Down Expand Up @@ -181,9 +175,13 @@ def myfunc():
if not have_module:
not_found_message = f"No module named '{fullname}'"
elif require is not None:
# Old style lazy loading to avoid polluting sys.modules
import packaging.requirements

try:
import importlib_metadata
except ImportError:
import importlib.metadata as importlib_metadata

req = packaging.requirements.Requirement(require)
try:
have_module = req.specifier.contains(
Expand All @@ -202,6 +200,8 @@ def myfunc():
if not have_module:
if error_on_import:
raise ModuleNotFoundError(not_found_message)
import inspect

try:
parent = inspect.stack()[1]
frame_data = {
Expand Down

0 comments on commit 10dffc6

Please sign in to comment.