Code style - “flattening” a package's namespace

 ̄綄美尐妖づ 提交于 2019-12-07 09:33:56

问题


My package hierarchy:

InstrumentController/
    __init__.py
    instruments/
        __init__.py
        _BaseInstrument.py
        Keithley2000.py
        # etc...

The contents of the instrument files:

# _BaseInstrument.py
class _BaseInstrument(object):
    """Base class for instruments"""
    # etc...

# Keithley2000.py
from InstrumentController.instruments._BaseInstrument import _BaseInstrument
class Keithley2000(_BaseInstrument):
    # etc...

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.

For this purpose I have a bunch of lines like this in InstrumentController.instruments.__init__:

from .Keithley2000 import Keithley2000
from .StanfordSR830 import StanfordSR830
# etc...

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.



来源:https://stackoverflow.com/questions/12626336/code-style-flattening-a-packages-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!