代码样式-“扁平化"包的名称空间 [英] Code style - "flattening" a package's namespace
问题描述
我的包裹层次结构:
InstrumentController/
__init__.py
instruments/
__init__.py
_BaseInstrument.py
Keithley2000.py
# etc...
仪器文件的内容:
# _BaseInstrument.py
class _BaseInstrument(object):
"""Base class for instruments"""
# etc...
# Keithley2000.py
from InstrumentController.instruments._BaseInstrument import _BaseInstrument
class Keithley2000(_BaseInstrument):
# etc...
我希望我的用户能够访问这些类而不必深入研究模块的层次结构.他们只需要键入from InstrumentController.instruments import Keithley2000
,而不是from InstrumentController.instruments.Keithley2000 import Keithley2000
.
I want my users to be able to access the classes without having to delve into a hierarchy of modules. They should just have to type from InstrumentController.instruments import Keithley2000
, not from InstrumentController.instruments.Keithley2000 import Keithley2000
.
为此,我在InstrumentController.instruments.__init__
中有一堆这样的行:
For this purpose I have a bunch of lines like this in InstrumentController.instruments.__init__
:
from .Keithley2000 import Keithley2000
from .StanfordSR830 import StanfordSR830
# etc...
因此,现在这些类位于包名称空间的 top 而不是子模块中.我的问题是:这是个好主意吗?这些类与它们所属的模块具有相同的名称,因此在顶级导入该类会使该模块不可用.这让我有些胆怯-有更好的方法吗?
So now the classes sit at the top of the package's namespace, rather than in submodules. My question is: is this a good idea? The classes have the same name as the modules to which they belong, so importing the class at the top level renders the module unavailable. This makes me a little squeamish - is there a better way of doing this?
推荐答案
您的做法是可以接受的,但是我建议您将所有程序包/模块名称的大小写改为1),即惯例
How you are doing it is acceptable, but I recommend that you recase all package/module names to lowercase as 1) that is the convention specified in PEP 8, and 2) it will remove your shadowing issue.
这篇关于代码样式-“扁平化"包的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!