【发布时间】:2020-01-17 15:22:38
【问题描述】:
我有一个面向对象的 Python 3.7 项目,其结构如下:
├── plugins
│ ├── book_management
│ │ ├── book_inserter.py
│ │ ├── book_remover.py
│ │ ├── __init__.py
│ │ ├── book.py
│ │ ├── book_sampler.py
│ │ ├── operators
│ │ │ ├── __init__.py
│ │ │ ├── register_book.py
│ │ │ ├── unregister_book.py
│ │ │ └── mark_book_as_missing.py
│ ├── __init__.py
│ ├── reader_management
│ │ ├── __init__.py
│ │ ├── reader.py
│ │ ├── reader_creator.py
│ │ ├── reader_emailer.py
│ │ ├── reader_remover.py
│ │ ├── operators
│ │ │ ├── __init__.py
│ │ │ ├── create_reader.py
│ │ │ ├── remove_reader.py
│ │ │ └── email_reader.py
├── tests
│ ├── __init__.py
│ ├── book_management_tests
│ │ ├── __init__.py
│ │ ├── test_book.py
│ │ ├── test_book_inserter.py
│ │ ├── test_book_remover.py
│ │ ├── test_book_sampler.py
│ │ ├── test_mark_book_as_missing_operator.py
│ │ ├── test_register_book_operator.py
│ │ ├── test_unregister_book_operator.py
│ ├── reader_management_tests
│ │ ├── __init__.py
│ │ ├── test_reader.py
│ │ ├── test_reader_creator.py
在像test_mark_book_as_missing_operator 这样的测试中,我最终得到了这样的导入:
from plugins.book_management.book_inserter import BookInserter
from plugins.book_management.operators.mark_book_as_missing import (
MarkBookAsMissingOperator
)
from plugins.reader_management.reader_creator import ReaderCreator
from plugins.reader_management.operators.create_reader import (
CreateReaderOperator
)
这些非常冗长的部分导入感觉非常糟糕。所以我猜我一定做错了。理想情况下,将plugins.reader_management 和plugins.reader_management.operators 导入可能更短的内容似乎更具可读性。
book_inserter.py 定义了一个类BookInserter。理想情况下,我想保留这种 1-class / 1-file 结构。显然,这会导致文件数量的膨胀,但也允许更短更集中的文件。但如果这完全不是 Pythonic,我愿意听听为什么以及如何调整代码结构。
最后我一直在使用这种多层架构 (plugins/*_management/operators/*.py),但这会导致很长的导入行,因此我经常遇到合法的 lint 问题。
我一直在考虑从顶级模块(如 book_management,book_management/__init__.py)导入子模块,但我不确定这是否是一种好的做法,而且这似乎违反了文件中没有未使用的导入的原则。 (我也会因此面临循环进口的风险吗?)
简而言之,我的主要问题是:构建这样一个项目并设置导入的(?)Pythonic 方式是什么(最好有一些理由说明为什么这是一种/Pythonic 方式)。
【问题讨论】:
标签: python python-3.x