How can a module know the module that imported it?

kj no.email at please.post
Wed Nov 11 16:55:58 EST 2009


In <hdf9bq$59s$1 at panix3.panix.com> aahz at pythoncraft.com (Aahz) writes:

>In article <hdf63i$cmp$1 at reader1.panix.com>, kj  <no.email at please.post> 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
>solution?

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/Module.pm:

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.

kynn



More information about the Python-list mailing list