Module loading trickery

Thomas Jollans thomas at jollybox.de
Tue Oct 5 12:06:36 EDT 2010


On Tuesday 05 October 2010, it occurred to Jonas Galvez to exclaim:
> Is there a way to "inject" something into a module right before it's
> loaded?
> 
> For instance, a.py defines "foo". b.py print()s "foo".
> 
> I want to load b.py into a.py, but I need to let b.py know about "foo"
> before it can execute.
> 
> Is this any way to achieve this?

No. That's just not how Python works. [*]
However, you can simply import foo from a explicitly within b. Though you 
might want to rethink what you're doing. Maybe.

% cat a.py
foo = 'Meh.'
import b

% cat b.py
from a import foo

print(foo)

% python a.py
Meh.
% 


 - Thomas

[*] Actually, it is possible with runpy. But don't. Really, don't, unless you 
have a very good reason to do so, and judging by the way the question was 
asked, I don't think you do.



More information about the Python-list mailing list