cannot have test scripts in packages?

Alan Isaac aisaac at american.edu
Thu Jun 21 23:30:29 EDT 2007


This is really a repackaging of an earlier question,
probably illustrating that I still do not understand relative imports.

Suppose I have the package structure (taken from the example at
http://www.python.org/dev/peps/pep-0328/)

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py

Important detail:
moduleZ uses a relative import to access moduleY.

The problem:
I have a script test.py that I want to
distribute with the package.  It will import
moduleZ to illustrate or test the module's use.

Is it the case that this script cannot reasonably be
bundled with `package`?  (I.e., within its directory
structure.)

I cannot put it in the `subpackage2` directory and
just import moduleZ, because then I will get
ValueError: Attempted relative import in non-package

I cannot put it in the `package` directory and
import subpackage2.moduleZ, because then I will get
ValueError: Attempted relative import beyond toplevel package

The script could then use path manipulation to
find `package`, as suggested by Alex Martelli
http://mail.python.org/pipermail/python-list/2007-May/438250.html
and others.  However it has also been claimed that this approach is an
insane for any shared code.

Btw, I do not want to assume the package will be installed:
a user should be able to play with it without installing it.

So if the package is not installed, is the only "sane"
thing to do is require any user to take the step of
inserting the package location into sys.path and have
test.py rely on the user having done this?

What is the recommended handling of demo or test scripts
for a package?

Thank you,
Alan Isaac





More information about the Python-list mailing list