How can a module know the module that imported it?

Christian Heimes lists at cheimes.de
Wed Nov 11 23:50:20 CET 2009


kj wrote:
> 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
> } 
> 

That's terrible style! Code should not react differently if you run it
inside an unit test harness. If you need to change the environment for
tests because you can test all aspects of your runtime environment, use
a mock up system. Please read
http://www.voidspace.org.uk/python/articles/mocking.shtml if you don't
know the term.

Christian




More information about the Python-list mailing list