7

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.

1 Answer 1

15

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 *.

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

1 Comment

Perfect, thank you. I didn't need to import *, selecting the functions worked fine. I didn't know doing this (from B import B) would put B into the package namespace as package.B. Though it's kind of obvious now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.