subpackage import problem

Robert Kern rkern at ucsd.edu
Sun Aug 21 09:36:43 CEST 2005


Eric Huss wrote:
> 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'

I imagine it has something to do with the timing of imports. Python is
executing the contents of foo/sub/B.py while it's trying to create the
module object foo.sub. You can get around it, though.

Try this in foo/sub/B.py :

  from foo.sub.A import A
  class B(A):
      pass

That works for me (Python 2.4.1, OS X).

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list