facebookincubator / cinder

Cinder is Meta's internal performance-oriented production version of CPython.
https://trycinder.com
Other
3.42k stars 122 forks source link

Add eager_imports context manager #81

Closed chuanzzx closed 2 years ago

chuanzzx commented 2 years ago

Summary

Add a context manager importlib.eager_imports() to make imports in it shallow eager.

Test Plan

I followed the functional spec of importlib.eager_imports() in PEP690 to implement this. Imports within context managers are always eager no matter with or without -L, so I built a null context manger for mportlib.eager_imports().

However, the context manager does not force all imports to be recursively eager. The (sub) imports in the imported module in context manager's scope will still be lazy if Lazy Imports is enabled.

Pre-req

Create test.py, foo.py and bar.py under the same path of python.exe.

test.py

import importlib

with importlib.eager_imports():
    import math
    import foo

import sys

print("Is `math` lazy?", importlib.is_lazy_import(globals(), "math"))
print("Is `foo` lazy?", importlib.is_lazy_import(globals(), "foo"))
print("Is `sys` lazy?", importlib.is_lazy_import(globals(), "sys"))

foo.py

print("foooooo.")
import os
import bar

bar.py

print("I'm bar!")

Test with Lazy Imports

Run

./python.exe -L test.py

Expected results: bar wasn't eagerly imported because the context manager eager_imports() only made import foo shallow eager.

foooooo.
Is `math` lazy? False
Is `foo` lazy? False
Is `sys` lazy? True

Test without Lazy Imports

Run

./python.exe test.py

Expected results: bar was also eagerly imported because we did not use Lazy Imports.

foooooo.
I'm bar!
Is `math` lazy? False
Is `foo` lazy? False
Is `sys` lazy? False