How can a module know the module that imported it?

kj at
Wed Nov 11 22:55:58 CET 2009

In <hdf9bq$59s$1 at> aahz at (Aahz) writes:

>In article <hdf63i$cmp$1 at>, kj  < at> wrote:
>>The subject line says it all.

>You are probably trying to remove a screw with a hammer

Worse: I'm trying to write Perl using Python!

>-- why don't you
>tell us what you really want to do and we'll come up with a Pythonic

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.

# 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.


More information about the Python-list mailing list