Python MVC – File Separation Best Practices

code-qualitydesign-patternspython

I'm used to programming in Java, so my view of these things is quite Java based but I doubt this is the correct way of writing Python code. I found this https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file link which asks a similar question to what I am about to ask.

In Python, when creating an MVC application, does it make sense to put all the classes in one file (module) as each part of the MVC application does technically belong together?

In Java, the idea would surely be to split these files as we might want to swap out either part of the MVC combination for another part. That is one of the advantages of writing MVC code (though in practice, might happen rarely). Still, I would opt to create a file for each part of the MVC code. A class for the model, view and controller.

Now, I can kind of get grouping objectGUI, objectModel, objectController in one module. As together they form object. But on the other hand, that feels kind of wrong from the Java background.

Is there a good rule of thumb for how splitting into modules actually works in Python. Is MVC even a strong thing in Python? (In my mind, Python is still mostly for glue code and scripts).

Best Answer

In Python, a file is a unit of import. So it makes sense to put things that belong together in the same file, and things that don't, to separate files.

Web frameworks like Django by default expect you to put your models in models.py, and your views / controllers in views.py. In large applications, these files are actually split, usually by subject area. Django also allows you to compose a whole web app from several reusable 'applications', each with its own structure.

It is easy to split a large file into several files without breaking existing code in Python. You just re-export the names from a split-out file, like this:

(views.py)

# These used to be defined here, now moved to premium_views.py 
from premium_views import FancyFeatureView, ExtraSnazzyView

class StandardView(...): ...

Now you can from views import FancyFeatureView, as if it were completely defined there. There's even a pattern of having such files that only re-export things from a bunch of other modules, so that these other modules can be changed as authors see fit without affecting normal client code.

Another consideration could be testing. What you want to test under significantly different setups likely belongs to different modules (files).

Related Topic