包裹“在...内"模组 [英] Packages "within" modules
问题描述
我越来越多的脚本组成了我正在编写的程序,并决定是时候清理我的源代码树并将其正确打包.我敢肯定这是一个简单的问题,但我找不到解决方法.
I have a growing number of scripts that make up a program I am writing and decided it was time to clean up my source tree and package them up correctly. I'm sure this is a simple question but I can't find out how to do it.
如果我有一组模块,这些模块可以组合在一起,但是一个模块应该是顶层模块,而其他模块应该以模块名称为前缀,但实际上要放入较低级别的软件包中,我该怎么做.
If I have a group of modules, that fit together, but one should be a top-level module and the others should be prefixed by the module name but actually go into lower level packages, how can I do it.
例如,说我希望能够import mystuff
,并得到所有的东西.但我也应该能够import mystuff.test.test1
.我以为我会像这样创建一个源代码树,
For example say I wanted to be able to import mystuff
, and get all mystuff. but I also should be able to import mystuff.test.test1
. I thought I would create a source tree like this,
myprogram/
mystuff.py
mystuff/
__init__.py
tests/
__init__.py
test1.py
test2.py
...
但是在这种情况下,似乎mystuff/
总是优先于mystuff.py
,因此import mystuff
不执行任何操作(只要mystuff/
的__init__.py
为空).
But in this case, it seems mystuff/
always takes precedence over mystuff.py
, so import mystuff
does nothing (as long as mystuff/
's __init__.py
is empty).
获得所需行为的正确方法是什么?或者这是不可能的,我必须将mystuff.py
移到mystuff/
并必须以mystuff.mystuff
的身份访问它(似乎是不必要的重复).
What would be the correct approach to get the desired behaviour? Or is this not possible and must I move mystuff.py
into mystuff/
and have to access it as mystuff.mystuff
( seem's like unnecessary repetion).
对不起,如果我只是想念一些明显的事情.我认为这必须在某个地方记录下来,但是我似乎找不到在哪里.
Sorry, if I've just missed something obvious. I assume this must be documented somewhere, but I can't seem to find where somewhere is.
更新.虽然我相信Ignacio的方法是正确的方法,但我真的不喜欢它!如果我在编辑器中打开了多个文件,并且它们都被称为__init__.py
,则事情可能会变得混乱.因此,我决定保持原样,将mystuff.py
链接到mystuff/__init__.py
.如果有人对我为什么不应该这样做有任何意见,我想听听他们的意见.
Update. While I believe Ignacio's method is the correct one, I don't really like it! If I have multiple files open in my editor and they're all called __init__.py
things could get messy. So, I have decided to leave my structure as it is, and link mystuff.py
to mystuff/__init__.py
. If anyone has any opinions on why I shouldn't be doing this, I'd like to hear them.
实际上,最后,我以另一种方式进行链接,因为在创建tar.gz
时无法找到使distutils取消引用符号链接的方法,并且最终在输出中出现了断开的链接.这种方法具有相同的效果并使它保持快乐状态.
Actually in the end, I am linking the other way around, since I couldn't find a way to make distutils dereference symlinks when creating a tar.gz
, and I ended up with broken links in my output. This way has the same effect and keeps it happy.
推荐答案
mystuff.py
中的所有内容都应放置在mystuff/__init__.py
中.
Everything in mystuff.py
should be placed into mystuff/__init__.py
instead.
这篇关于包裹“在...内"模组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!