noio
noio

Reputation: 5812

Pulling python module up into package namespace

If I have a directory structure like this:

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 do I make the contents of functions, classes, accessible as:

p.do()
p.A()

in stead of:

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

The subdivision in files is only there for convenience (allowing easier collaboration), but I'd prefer to have all the contents in the same namespace.

Upvotes: 7

Views: 609

Answers (1)

user395760
user395760

Reputation:

You could do this in __init__.py (because that's what you import when you import package):

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

However, import * is nearly always a bad idea and this isn't one of the exceptions. Instead, many packages explicitly import a limited set of commonly-used names - say,

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

This too allows accessing do or A directly, but it's not nearly as prone to name collisions and the other problems that come from import *.

Upvotes: 15

Related Questions