简体   繁体   中英

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).

I have this very basic project structure, using the simplest form of MVC I can muster:

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:

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. 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.

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. There's no fundamental difference between these:

from django.db import models

from myproject.controllers import controller

django is a globally installed package. myproject should be a globally installed package.

If wouldn't make sense to have a global " controllers " module floating around, it should clearly be part of a larger package.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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