I don't really have any knowledge of the Python interpreter's
internals so I'm afraid any suggestions of mine on implementation
details are going to be shots in the dark.
said, my intuition tells me that something similar to the proxy object
pattern currently used by many lazy import implementations maybe could
work here, with the interpreter creating some sort of 'lazy import
proxy' object on this line rather than performing the import:
> from .extremely_expensive_module lazy import SomeClass
And then when it actually is used in any way as part of any code that isn't another lazy import statement
(normal import statements and even assignment statements that don't
modify the object or attempt to access its attributes would count) it
actually gets fully imported at that point in time, and all references
anywhere in the application to this 'lazy import proxy' are swapped to
point at the real object.
You could have it
so that if you tried to lazy import an object that is actually already a
'lazy import proxy' you would just get a reference to it rather than
provisioning a new one. This would allow you to 'chain' lazy import
statements across several modules to defer the import until the object
(be it a module or a class) is actually used.
I don't know enough about the implementation of the interpreter I
couldn't really say if there's a way that normal objects could just be
treated precisely as they are now with no loss of performance, while
still giving 'lazy import objects' their special treatment. I suppose
that's part of the point of this discussion. Hopefully people who know
more can chime in.
I definitely do think
that there would be value in allowing all objects to be lazily imported
via support for the 'from x import y' statement, not just modules, but I
accept this is something people will have their own opinions on, and
that mine isn't special. My earlier examples highlight situations where I
think a lazy implementation of the normal 'import x' statement wouldn't
be enough, and 'from x import y' would be needed.