I've a Python project with ~30 SQLAlchemy models and I'm not sure where they belong. All models belong to the DB but also to a module, so I'm not sure about the right namespace.

Here are some ideas:

  1. import db.models.MyModelA
  2. import my.module.MyModelA
  3. import my.module.db.MyModelA

Is there any best practice that I didn't find yet? I think this is a software design/architecture issue and not necessarily limited to Python.

Any advice is appreciated. Thanks.

  • Which approach best meets your project's specific non-functional requirements? – Robert Harvey Feb 5 at 14:49

Actually, your question has hundreds of correct answers. because it's completely related to your application scope and design. Let's review the definition of "Best Solution" in this case. The structure of your files needs to be organized enough to avoid confusion, conflicts, and misuse and they Must Be meaningful, useful, maintainable, and reusable.

So make the situation clear for yourself. Do you have any other Classes like DTOs that need to be placed into the model's directory or not? if put different groups of files with different usage and structure in the same directory, they should be clearly separated by some naming conventions like prefix/suffixes.

Solution #1

--UserDB.py // what you are going to use for your ORM
--UserDTO.py // what you are going to return in the response of your API.

Solution #2

-- DB
---- User.py
-- DTO
---- User.py

In this solution, you might encounter a situation that you need to import one of them somewhere, and then you can import one of them wrongly or if you need both of them, you need to use an alias for them and it makes confusion for the other developers.

Solution #3

-- DB
---- UserDB.py
-- DTO
---- UserDTO.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.