Given a function defined inline, how do I get getsource
to provide the output? - This is for a test, here's the kind of thing I'm trying:
from importlib.util import module_from_spec, spec_from_loader
_locals = module_from_spec(
spec_from_loader("helper", loader=None, origin="str") # loader=MemoryInspectLoader
)
exec(
'def f(): return "foo"',
_locals.__dict__,
)
f = getattr(_locals, "f")
setattr(f, "__loader__", MemoryInspectLoader)
With my attempt, as it looks like a linecache
issue:
from importlib.abc import Loader
class MemoryInspectLoader(Loader):
def get_code(self): raise NotImplementedError()
But the error is never raised. From getsource(f)
, I just get:
In [2]: import inspect
...: inspect.getsource(f)
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-3-1348c7a45f75> in <module>
----> 1 inspect.getsource(f)
/usr/lib/python3.8/inspect.py in getsource(object)
983 or code object. The source code is returned as a single string. An
984 OSError is raised if the source code cannot be retrieved."""
--> 985 lines, lnum = getsourcelines(object)
986 return ''.join(lines)
987
/usr/lib/python3.8/inspect.py in getsourcelines(object)
965 raised if the source code cannot be retrieved."""
966 object = unwrap(object)
--> 967 lines, lnum = findsource(object)
968
969 if istraceback(object):
/usr/lib/python3.8/inspect.py in findsource(object)
796 lines = linecache.getlines(file)
797 if not lines:
--> 798 raise OSError('could not get source code')
799
800 if ismodule(object):
OSError: could not get source code
How do I make getsource
work with an inline-defined function in Python 3.6+?