lazy_import icon indicating copy to clipboard operation
lazy_import copied to clipboard

Unexpected module import when using `inspect`

Open jeremander opened this issue 2 years ago • 0 comments

Ordinarily, accessing attributes on a LazyModule triggers the import, but sometimes this can happen unexpectedly. One such case happens with the __file__ attribute. Here is a minimal example.

fail.py

raise ValueError('Boom!')

script.py

import inspect
from lazy_import import lazy_module

fail = lazy_module('fail')
frame = inspect.currentframe()
mod = inspect.getmodule(frame)

Running the above script triggers the import (and hence, the error). This results from inspect checking the __file__ attribute of every module in sys.modules, including fail. The behavior is undesirable since the user did not intentionally access any attribute of fail.

To fix this, one could simply add '__file__' to the list of exemptions in LazyModule.__getattribute__.

jeremander avatar May 27 '22 00:05 jeremander