如何避免类/方法/等的多个位置。在一个python包的命名空间中?考虑一个包含以下目录结构和代码的包:禁止子模块出现在名称空间w/__init__.py
dummyproj/
├── __init__.py
└── main.py
。
# main.py
# =======
def dummy_func():
print "hello world"
。
# __init__.py
# ===========
from main import *
有了这种结构,函数dummy_func
可在包中找到。但是,它也可以从名为main
的子模块中获得。例如:
>>> import dummyproj
>>> dir(dummyproj)
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__path__',
'dummy_func',
'main']
>>> dummyproj.dummy_func()
hello world
>>> dummyproj.main.dummy_func()
hello world
我将如何防止main
不再出现在dummy_proj
命名空间呢?我的理解是,将dummy_func
的代码包含在__init__.py
中将是错误的形式。
因此,尽管'dummy_func'出现在两个地方,那么这是一种可以接受的做法吗? – 2014-09-21 22:04:16
感谢您的帮助,卢卡斯。我对'requests'模块有点熟悉,所以这是一个有效的例子。你介意提交一些这样的答案作为答案,这样我可以将其标记为接受? – 2014-09-21 22:18:34