简体   繁体   English

为什么从同级包中导入模块被视为反模式?

[英]Why is importing a module from a sibling package considered an anti-pattern?

I just started learning how to code in Python (came from a Java background).我刚开始学习如何用 Python 编写代码(来自 Java 背景)。

I have this very basic project structure, using the simplest form of MVC I can muster:我有这个非常基本的项目结构,使用我可以召集的最简单的 MVC 形式:

myproject
    controllers
        __init__.py
        controller.py
    models
        __init__.py
        model.py
    views
        __init__.py
        view.py
    main.py

Provided that I start with view.py and I need to make a link between this and its controller, I know that I have to import the controller by using the import commands:假设我从 view.py 开始并且我需要在它和它的控制器之间建立一个链接,我知道我必须使用导入命令来导入控制器:

from controllers import controller

I know for a fact that this doesn't work, so I use relative paths in order to try and make it work.我知道这是行不通的,所以我使用相对路径来尝试使其工作。

from ..controllers import controller

I also know that this doesn't work as it can't really see the folder, in order to fix that I need to make the myproject folder a package in and of itself.我也知道这不起作用,因为它无法真正看到文件夹,为了解决这个问题,我需要将 myproject 文件夹本身设置为一个包。 But this doesn't make sense to me.但这对我来说没有意义。

I read somwehere that this kind of file structure is an "anti-pattern" almost.我在这里读到这种文件结构几乎是一种“反模式”。 But why though?但为什么? MVC is structurally sound by decoupling their functions, so separating them into their own packages makes sense. MVC 通过解耦它们的功能在结构上是合理的,因此将它们分离到自己的包中是有意义的。

You must not think in terms of "files", but in terms of packages .你不能从“文件”的角度思考,而是从包的角度思考。 Your entire project should be its own package which is installed in your Python environment like any other package.你的整个项目应该是它自己的包,它像任何其他包一样安装在你的 Python 环境中。 There's no fundamental difference between these:这些之间没有根本区别:

from django.db import models

from myproject.controllers import controller

django is a globally installed package. django是一个全局安装的包。 myproject should be a globally installed package. myproject应该是一个全局安装的包。

If wouldn't make sense to have a global " controllers " module floating around, it should clearly be part of a larger package.如果让一个全局的“ controllers ”模块四处漂浮是没有意义的,它显然应该是一个更大的包的一部分。

Within a package you can do relative imports if you want to, which is mostly shorthand and perhaps helps a bit if you rename the top level package, but is otherwise inconsequential.在一个包中,如果你愿意,你可以进行相对导入,这主要是速记,如果你重命名顶级包可能会有所帮助,但在其他方面是无关紧要的。

Always think in terms of eventually publishing your package to PyPI or building a wheel which you distribute to production servers for installation, even if you're never going to do either of those things.始终考虑最终将您的包发布到 PyPI 或构建一个您分发到生产服务器进行安装的轮子,即使您永远不会做这些事情中的任何一件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM