简体   繁体   中英

python - import namespace

If I have a library like:

MyPackage:

  • __init__.py

  • SubPackage1

    • __init__.py
    • moduleA.py
    • moduleB.py
  • SubPackage2
    • __init__.py
    • moduleC.py
    • moduleD.py

But I want that users can import moduleA like import MyPackage.moduleA directly. Can I implement this by write some rules in MyPackage/__init__.py ?

In MyPackage/__init__.py , import the modules you want available from the subpackages:

from __future__ import absolute_import  # Python 3 import behaviour

from .SubPackage1 import moduleA
from .SubPackage2 import moduleD

This makes both moduleA and moduleD globals in MyPackage . You can then use:

from MyPackage import moduleA

and that'll bind to the same module, or do

import MyPackage

myPackage.moduleA

to directly access that module.

However, you can't use

from MyPackage.moduleA import somename

as that requires moduleA to live directly in MyPackage; a global in the __init__ won't cut it 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