[Python-ideas] Provide a way to import module without exec body

Serhiy Storchaka storchaka at gmail.com
Sun Dec 3 01:58:11 EST 2017

01.12.17 20:12, Neil Schemenauer пише:
> On 2017-12-01, Chris Angelico wrote:
>> Can you elaborate on where this is useful, please?
> Introspection tools, for example, might want to look at the module
> without executing it.  Also, it is a building block to make lazy loading
> of modules work.  As Nick points out, importlib can do this already.
> Currently, the IMPORT_NAME both loads the code for a module and also
> executes it.  The exec happens fairly deep in the guts of importlib.
> This makes import.c and ceval.c mutually recursive.  The locking gets
> complicated.  There are hacks like _call_with_frames_removed() to hide
> the recursion going on.
> Instead, we could have two separate opcodes, one that gets the module
> but does not exec it (i.e. a function like __import__() that returns a
> future) and another opcode that actually does the execution.  Figuring
> out all the details is complicated.

The IMPORT_NAME opcode is highly optimized. In most cases it just looks 
up in sys.modules and check that the module is not imported right now.
I suppose two opcodes will hit performance. And I don't see how this 
could simplify the code.

I suppose the existing importlib machinery already supports loading 
modules without executing them. Maybe not with a single function, but 
with a combination of 2-3 methods. But what you want to get? The source? 
The code object? What about modules implemented in C?

More information about the Python-ideas mailing list