How can a module know the module that imported it?

Diez B. Roggisch deets at
Wed Nov 11 23:47:31 CET 2009

> Because the problem that gave rise to this question is insignificant.
> I would want to know the answer in any case.  *Can* it be done in
> Python at all?


> OK, if you must know:
> With Perl one can set a module-global variable before the module
> is loaded.  This provides a very handy backdoor during testing.
> E.g.
> # in t/some_test.t script
> ...
> BEGIN { $My::Module::TESTING = 1; }
> use My::Module;
> ...
> and in My/
> package My::Module;
> our $TESTING ||= 0;  # set to 0 unless already initialized to !0 
> ...
> if ($TESTING) {
>   # throw testing switches
> } 
> This does not work in Python, because setting my.module.TESTING
> variable can happen only after my.module has been imported, but by
> this point, the module's top-level code has already been executed,
> so setting my.module.TESTING would have no effect.  But one way to
> get a similar effect would be to have my.module set its TESTING
> (or whatever) variable equal to the value of this variable in the
> *importing* module.

I don't understand enough (actually nothing) from perl, but I *am* a 
heavily test-driven developer in Python. And never felt that need.

Sure, sometimes one wants to change behavior of a module under test, 
e.g. replacing something with a stub or some such.

But where is the problem doing

--- ---

import moduletobetested as m

m.SOME_GLOBAL = "whatever"




More information about the Python-list mailing list