开发者

Pulling python module up into package namespace

开发者 https://www.devze.com 2023-02-02 19:17 出处:网络
If I have a directory structure like this: package/ __init__.py functions.py#contains do() classes.py#contains class A()

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

精彩评论

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