Pulling a python module into a package namespace

If I have a directory structure such as:

package/ __init__.py functions.py #contains do() classes.py #contains class A() 

And I want to be able to call

 import package as p 

How to make the contents of functions , classes available as:

 p.do() pA() 

instead

 p.functions.do() p.classes.A() 

The unit in the files is available only for convenience (which makes it easier to interact), but I would prefer to have all the contents in the same namespace.

+7
source share
1 answer

You can do this in __init__.py (because this is what you import when you import package ):

 from package.functions import * from package.classes import * 

However, import * almost always a bad idea , and this is not one of the exceptions. Instead, many packages explicitly import a limited set of common names - say,

 from package.functions import do from package.classes import A 

It also allows you to directly access do or A , but it’s not as strong as conflicts and other problems arising from import * can be called.

+13
source

All Articles