简体   繁体   中英

Confusion with __init__.py and importing classes in parent module from submodule

I'm having a little difficulty understanding how to import classes from a parent module from within a submodule. I have the following directory structure:

   module/
      __init__.py        (1)
      common.py          (containing testfunc and CommonClass)
      submod/
         __init__.py     (2)
         test.py         (containing TestClass)

in (1) I have:

   from common import *

So I can do directly:

   import module
   module.testfunc()

in (2) I have:

   from test import TestClass

So from within module I can do:

   import submod
   class_inst = submod.TestClass()

Now in TestClass (contained in test.py ) I want to use an instance of CommonClass , so I tried first importing it using:

   from ..common import *

Which works fine, but when I try to create an instance of CommonClass in TestClass :

   class TestClass(object):
       def __init__(self):
           self.inst = CommonClass()

I get the error:

   NameError: global name 'CommonClass' is not defined

Similarly if I try instead from ..common import CommonClass I get the error:

   ImportError: cannot import name CommonClass

As far as I can tell, CommonClass should be visible from within test.py , so I'm not sure why it can't be found. I have a feeling there is something I'm not understanding about the usage of __init__.py . Is there anyone who can help by pointing out any obvious mistakes I am making?

I'd like to say "circular imports" but I can't quite pinpoint it. The ImportError you're seeing might well be a symptom of that. Generally, if you import a module which in turn imports something else, and the import chain ends up importing the very module that started all the importing, you'll get an ImportError.

Can you move CommonClass into a new module module.submod.utils that doesn't import anything else from your code and import it from there?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM