Usual practice: running/testing modules in a package

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Aug 26 03:16:56 CEST 2008


--- El dom 24-ago-08, Medardo Rodriguez (Merchise Group)  
<med.swl at gmail.com> escribió:

(please keep posting on this list)

> On Sun, Aug 24, 2008 at 1:18 AM, Gabriel Genellina  
> <gagsl-py2 at yahoo.com.ar> wrote:

>> I think you misunderstood the comment.
> I didn't. The problem is my bad English :(
I'm not a native English speaker either...

> What you say in this mail is valid, my point is not related
> to the way
> we organize a python package in submodules and how it's
> executed the
> "__init__.py" to initialize it or to define
> structures a package
> level.
> My problem is about style. It is my wish to implement
> module tests in
> the same module after "if __name__ ==
> '__main__':" and to test each
> module in every moment I feel nice to do it (I widely use
> "Test-driven
> development").
> Of course I move the test code to package
> "__init__.py" when it
> depends on relative imports. Maybe the solution is to
> formalize a way
> in order IDE plug-ins, like Eclipse PyDev could make this
> easy.

I see. Unfortunately it doesn't work in this situation:

- you want to test a module inside a package
- the module uses relative imports
- you want the test code to reside on the same module, using "if __name__  
== '__main__'"

Because if you run the module as a script (to execute the "if __name__ ==  
..." section) Python can't recognize that the module is contained inside a  
package, and in that case relative imports don't work.
You may avoid any of the last two conditions:

- don't use relative imports. That might work, but leaves another problem:  
in the production environment, the module *will* be part of a package. In  
the testing environment, it is not. The difference may be relevant in some  
cases (relative imports are just one of the differences).

- don't put the test code on the same module. Use another script that  
first imports the package and then executes the test. As you said,  
probably some Eclipse plugin can help automate this setup - I don't know,  
I don't use Eclipse myself. PyScripter does support it  
<http://pyscripter.googlecode.com/>

-- 
Gabriel Genellina




More information about the Python-list mailing list