subpackage import problem

Eric Huss e-huss at netmeridian.com
Sun Aug 21 09:07:28 CEST 2005


I'm having a problem with packages within packages.  Here's an example:

foo/
foo/__init__.py: empty file
foo/sub/__init__.py:
	from foo.sub.B import B
foo/sub/A.py:
	class A:
		pass
foo/sub/B.py
	import foo.sub.A
	class B(foo.sub.A):
		pass

Trying to "import foo.sub" will result in this error:

>>> import foo.sub
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "foo/sub/__init__.py", line 1, in ?
    from foo.sub.B import B
  File "foo/sub/B.py", line 3, in ?
    class B(foo.sub.A):
AttributeError: 'module' object has no attribute 'sub'

This can be fixed using a relative import in B.py, but I don't feel
comfortable with relative package imports (unintentional shadowing of
modules you want to use in the future, and the symantics might change in
the future due to PEP 328).

Does anyone have any suggestions?

The situation this comes up is:
- Have package foo with module bar.
- Module bar has a large number of classes.
- I want to break bar up into multiple files because it is getting too
large.
- In order to keep these classes together, I create a subpackage with a
separate file for each class.
- I import these files in the subpackage __init__.py so I don't have to
change any other code and so I don't have
foo.bar.flashlight.flashlight() lines where the word
"flashlight" is repeated.

-Eric



More information about the Python-list mailing list