Usual practice: running/testing modules in a package
gagsl-py2 at yahoo.com.ar
Sun Aug 24 07:18:14 CEST 2008
En Fri, 22 Aug 2008 17:31:58 -0300, Medardo Rodriguez (Merchise Group) <med.swl at gmail.com> escribió:
> On Fri, Aug 22, 2008 at 1:25 PM, Gabriel Genellina
> <gagsl-py2 at yahoo.com.ar> wrote:
>> what if __init__.py 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 "__init__.py" 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 test.py 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 test.py is contained inside a package. Looking for an __init__.py 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 __init__.py is executed and a new module object is placed in sys.modules.
So, when test.py is run directly, what to do with the code in __init__.py? 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 test.py, of course, but now Python *knows* that test.py lives inside a package and relative imports work fine now.
More information about the Python-list