Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Created May 28, 2026 13:32
Show Gist options
  • Select an option

  • Save pythonhacker/52bc1c936c7088aca192e60c26816702 to your computer and use it in GitHub Desktop.

Select an option

Save pythonhacker/52bc1c936c7088aca192e60c26816702 to your computer and use it in GitHub Desktop.
Example of doing lazy imports before Python 3.15
import importlib.util
import sys
import time
def lazy_import(name):
# Find module spec
spec = importlib.util.find_spec(name)
# Wrap loader with LazyLoader
loader = importlib.util.LazyLoader(spec.loader)
spec.loader = loader
# Create module object
module = importlib.util.module_from_spec(spec)
# Register in sys.modules
sys.modules[name] = module
# This does NOT execute module yet
loader.exec_module(module)
return module
# Measure imports
start_imports = time.time()
torch = lazy_import("torch")
transformers = lazy_import("transformers")
pd = lazy_import("pandas")
pyplt = lazy_import("matplotlib.pyplot")
sns = lazy_import("seaborn")
end_imports = time.time()
print(f"[DEBUG] Import time: {end_imports - start_imports:.2f} sec")
# To show that this works!
data = ["Good","Nice","Not good", "Bad"]
df = pd.DataFrame({"text": data})
print(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment