[Tutor] Help with packages and namespaces please

Andrew Wu andrewwu at gmail.com
Fri Oct 12 21:48:56 CEST 2007


Hi all,

I'm new to the list and relatively new to python, and very new to the use
and creation of packages.

Let's say I have these files in one directory:

PrintBase.py
PrintHello.py
PrintBye.py

PrintBase defines a very simple base class PrintBase, whose __init__ method
initializes a member to an optionally provided string (otherwise the string
is empty) and whose PrintMe method prints the string given (or empty string
otherwise).
PrintHello defines a class that inherits from PrintBase and whose PrintMe
method prepends a 'Hello, ' to the provided string.
PrintBye defines a class that inherits from PrintBase and whose PrintMe
method prepends a 'Good-bye' to the provided string.

Since all the files are in the same directory, I can use import statements
like from PrintHello import PrintHello ...

I'd like to reorganize the files so they're like the Sound example in the
Python tutorial:

PrintMe/
PrintMe/PrintBase/PrintBase.py
PrintMe/PrintHello/PrintHello.py
PrintMe/PrintBye/PrintBye.py

I've created empty __init__.py files in each of the subdirectories.  Here I
run into a number of problems and get confused - my goal is to keep the
import statements as they are (the actual files I'd be editing are many and
I'd rather avoid having to edit them all) - is there something I can put in
the __init__.py files so that the modules are brought into namespace w/o
having to use absolute module notation?

As simple tests, I've tried running different import commands in the python
interpreter:

I've tried adding the absolute directory paths to __path__ in each
__init__.py per subdirectory, and adding the paths to sys.path.  When I do
that and run the python intepreter and try 'from PrintMe.PrintHello import
PrintHello' I get an error saying 'Error when calling the metaclass bases,
module.__init__() takes at most 2 arguments (3 given)'.  The same code
functioned fine when all the files were in the same directory, so I'm
confused about why the interpreter thinks I'm passing 3 arguments along.

W/o those directories in sys.path I get an import error (there is no module
named 'PrintBase').  Also, if I'm in one of the subdirectories I get a
similar error when attempting to import the toplevel (PrintMe) package.

(Essentially I would like to structure the directories (er package?) so that
files in one subdirectory can subclass base classes from a sibling (not
parent) directory, ideally in a way that doesn't require each file to state
something like 'from 'PrintMe.PrintHello ... import ...' but instead 'from
PrintHello import ...'.  Is this possible, and if so how can I go about
doing it?)



Many Thanks!

Andrew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071012/bd026268/attachment-0001.htm 


More information about the Tutor mailing list