开发者

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:

开发者_StackOverflow
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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜