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 `importlib.set_lazy_imports()` #79

Closed chuanzzx closed 2 years ago

chuanzzx commented 2 years ago

Summary

Add importlib.set_lazy_imports() to enable Lazy Imports in runtime.

Test Plan

Start without Lazy Imports

Run

$ ./python.exe
>>> import importlib

If we import json, it should not be lazy.

>>> import json
>>> importlib.is_lazy_import(globals(), "json")
False

Then, we use importlib.set_lazy_imports() to enable Lazy Imports. If we import math now, it should be lazy.

>>> importlib.set_lazy_imports()
>>> import math
>>> importlib.is_lazy_import(globals(), "math")
True

If we use math.pi, it would be loaded.

>>> math.pi
3.141592653589793
>>> importlib.is_lazy_import(globals(), "math")
False

Start with Lazy Imports

Run

$ ./python.exe -L
>>> import importlib

If we import math, it should be lazy because we starts with -L.

>>> import math
>>> importlib.is_lazy_import(globals(), "math")
True

If we use math.pi, it would be loaded.

>>> math.pi
3.141592653589793
>>> importlib.is_lazy_import(globals(), "math")
False

If we use importlib.set_lazy_imports(), the behavior will not change. If we import json immediately, json is still lazy.

>>> importlib.set_lazy_imports()
>>> import json
>>> importlib.is_lazy_import(globals(), "json")
True

Wrong numbers of arguments

importlib.set_lazy_import() should not have any argument. No matter with or without -L, if we give it any argument, it will return the error message.

>>> importlib.set_lazy_imports(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: set_lazy_imports() takes 0 positional arguments but 1 was given