I’m trying to structure my app in Python. Coming back from C#/Java background, I like the approach of one class per file. I’d like my project tree to look like this:
[Service]
[Database]
DbClass1.py
DbClass2.py
[Model]
DbModel1.py
DbModel2.py
TheService.py
[ServiceTests]
[Database]
DbClass1Tests.py
DbClass2Tests.py
[Model]
DbModel1Tests.py
DbModel2Tests.py
TheServiceTests.py
- Is the one class per file approach OK in Python?
-
Is it possible to create packages/modules in such a way so that packages work like Java’s packages or .NET’s namespaces, i.e. in DbModel1Tests.py:
import Service.Model def test(): m = DbModel1()
In my opinion, for 1: I don’t see why not. I think, regardless of language this is a good idea as it provides you with a quick overview of what is to be found in a file when you know there will be only a single class in it. I would make a small exception for helper classes though, but as Python allows nested classes this can also be done quite nicely.
For 2: possible as well. In your example though, you simple load the module, thereby making its classes and functions available by the full namespace.
So, if you say
import Service.Model, you can only access the class by usingm = Service.Model.DBModel1().To import things into the current namespace, do a
from Service.Model import *(orfrom Service.Model import DBModel1if you only need that class). Then you can do as you currently do:m = DBModel1().