[Import-sig] import question

Guido van Rossum guido@digicool.com
Fri, 16 Mar 2001 21:13:14 -0500


> if I have the follwoing packages hierarchy
> 
> A/
> 	__init__.py
>         B/
> 		__init__.py
> 		C.py
> 
> 
> I can use:
> 
> >>> from A.B import C
> 
> but if I use:
> 
> >>> import A
> >>> print A
> <module 'A' from 'A/__init__.pyc'>
> >>> from A import B
> print B
> <module 'A.B' from 'A/B/__init__.py'>
> >>> from B import C
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> ImportError: No module named B
> 
> in order to get this to work I have to
> 
> >>> import sys
> >>> sys.modules['B'] = B
> 
> Is that expected ?
> In the documentation I read:
> 
> "from" module "import" identifier
> 
> so I expected "from B import C" to be legal since B is a module
> 
> I tried this with Python 1.5.2 and 2.0 on an sgi under IRIX6.5
> 
> Thanks for any help
> 
> -Michel

In "from X import Y", X is not a reference to a name in your
namespace, it is a module name.  The right thing is indeed to write
"from A.B import C".  There's no way to shorten this; what you did
(assigning sys.modules['B'] = B) is asking for trouble.

Sorry!

--Guido van Rossum (home page: http://www.python.org/~guido/)