How to import only one module in a package when the package __init__.py has already imports the modules?

Peng Yu pengyu.ut at gmail.com
Sat Oct 31 12:07:17 EDT 2009


I have the following files, which are in the directory 'test'. The
parent directory of 'test' is in $PYTHONPATH. I have 'from A import A'
and 'from B import B' in '__init__.py', because I want to use 'test.A'
and 'test.B' to refer to classes A and B rather than 'test.A.A' and
'test.B.B'.

$ll -g
total 24
-rw-r--r-- 1 staff  32 2009-10-31 10:41:47 __init__.py
-rw-r--r-- 1 staff 235 2009-10-31 10:45:24 __init__.pyc
-rw-r--r-- 1 staff 550 2009-10-31 10:45:24 B.pyc
-rw-r--r-- 1 staff 550 2009-10-31 10:45:24 A.pyc
-rw-r--r-- 1 staff  54 2009-10-31 10:46:03 A.py
-rw-r--r-- 1 staff  54 2009-10-31 10:46:14 B.py
$cat __init__.py
from A import A
from B import B
$cat A.py
class A:
  def __init__(self):
    print '__init__ A'
$cat B.py
class B:
  def __init__(self):
    print '__init__ B'


Then I have the following python files to call the modules. However,
because I have 'import A from A' in '__init__.py', I can not call
'test.A.A()' anymore. Even I only have 'import test.A', both modules
'A' and 'B' are imported. So 'import test.A' is essentially the same
as 'import test'.

I'm wondering if there is a way to make the following two things hold.
Thank you1
1. When I 'import test', I can refer to class A as 'test.A'.
2. When I 'import test.A', I can refer to class A as 'test.A.A' and
class B shall not be imported.



$cat fail.py
import test.A
test.A.A()
$python fail.py
Traceback (most recent call last):
  File "fail.py", line 2, in <module>
    test.A.A()
AttributeError: class A has no attribute 'A'
$cat main.py
import test
test.A()
test.B()
$python main.py
__init__ A
__init__ B
$cat fail2.py
import test.A
test.A()
test.B()
$python fail2.py
__init__ A
__init__ B



More information about the Python-list mailing list