subpackage import problem

E

Eric Huss

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:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top