简体   繁体   中英

Python Subpackages not available for import

I'm working from the basis of this previously posted problem: module importing itself

Essentially, that problem is solved, but in the "modulename.py" file, there is a class defined, with an init function, and a ui function. Inside the class, any line of the form:

import submodule

Will function just fine. However..

import submodule.subsubmodule

or

import subsubmodule

Will produce an ImportError.

All submodules and subsubmodules have an

__init__.py

file.

This often happens if you have multiple modules with the same name inside a package.

For example, consider:

mypkg/
  __init__.py
  toplevel.py
  mypkg.py

If the toplevel.py file calls import mypkg.mypkg , it will actually be importing the mypkg.py file and not the package.

You can solve this by including from __future__ import absolute_import as the first line in toplevel.py , which will force it to import the top-level package.

Alternatively, you can use from . import mypkg from . import mypkg in toplevel.py , which will explicitly import the mypkg.py file.

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