Usual practice: running/testing modules in a package

Gabriel Genellina gagsl-py2 at
Sun Aug 24 07:18:14 CEST 2008

En Fri, 22 Aug 2008 17:31:58 -0300, Medardo Rodriguez (Merchise Group) <med.swl at> escribió:

> On Fri, Aug 22, 2008 at 1:25 PM, Gabriel Genellina
> <gagsl-py2 at> wrote:
>> what if contains code?
> Thats what I usually do to solve the "problem", but for my taste it's
> better to write the test code of a module inside it.
> The code I write in "" is related to structures of
> initializations, globals at package level.
> if __name__ == "__main__":
>     pass # Here I test only concepts related to the entire package,
> not to any module.

I think you misunderstood the comment.
Suppose this setup:


When someone executes directly, currently Python doesn't know that it is contained inside a package, and some forms of relative imports don't work.
To make relative imports work, Python should be aware that is contained inside a package. Looking for an file at the same directory may reveal that there is a package - but that's not enough, because when a package is actually imported, its is executed and a new module object is placed in sys.modules.
So, when is run directly, what to do with the code in should it be executed, and when? I don't know the actual reasons, but this seems enough trouble to me to NOT automatically recognize a package unless someone actually imports it.

The application will import the package anyway, so why would the test code not do the same thing? I want to mimic the production environment as closely as possible in the testing environment. And the easiest way to do that is to "import SomePackage" in a script placed at SomeDir. The actual tests may reside in, of course, but now Python *knows* that lives inside a package and relative imports work fine now.

Gabriel Genellina

More information about the Python-list mailing list