0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.