Alan Isaac wrote: > This is a simple question about actual practice. > I just want to know how you (yes you) are > approaching this problem. > The problem: > What is the recommended packaging of > demo scripts or test scripts for a package > to be distributed to others to "play with". > (I.e., without "installing".) > > Example: > Suppose I have the package structure: > > package/ > __init__.py > subpackage1/ > __init__.py > moduleXX.py > subpackage2/ > __init__.py > moduleYY.py > > Important detail: > moduleXX uses a relative import to access moduleYY. > > The goal: > I have a script test.py that I want to > distribute with the package. This script will import > moduleXX 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.) > > Note: > If I put it in the `subpackage1` directory and > just import moduleXX, I will get > ValueError: Attempted relative import in non-package > > Note: > If I put it in the `package` directory and > import subpackage1.moduleXX, I will get > ValueError: Attempted relative import beyond toplevel package > > Here is one hack, based on a suggestion of Alex Martelli > http://mail.python.org/pipermail/python-list/2007-May/438250.html > and others. > - add a `scripts` subdirectory to `package` > - use path manipulation to find the directory holding `package` > - insert this directory in sys.path > > This hack "works". > However it has also been claimed that this approach is an > insane for any shared code. Is it? If so, what is best practice?
I have used this method more than once to get around the fact that relative imports don't work the way I want them to in this situation. Alternatively, you could use... package/ __init__.py #for 'import package' test.py shared/ __init__.py subpackage1/ __init__.py moduleXX.py subpackage2/ __init__.py moduleYY.py And always run scripts from the package/... path or from something that is able to 'import package'. It does force a layer of useless namespace, but it works. - Josiah -- http://mail.python.org/mailman/listinfo/python-list