mercredi 23 décembre 2020

What's the pythonic way of designing common class definitions in a package?

I'm coming from a C# background and have recently started to pick up Python 3. One thing that has lead to quite a bit of confusion so far has been how to structure modules in a package.

In C#, I would create a namespace MyLibrary.Model, in which all my different commonly used classes would reside, such as User, Employee, Customer, etc.. Each of these classes would be in their own file (e.g. User.cs, Employee.cs, etc.), since C# really doesn't care about files at all and only cares about which namespace a class belongs to. I would then import this in the various other bits of the library with using MyLibrary.Model, and all classes in that namespace would be available.

I have noticed that this is not how Python 3 likes to do things. Specifically, statements like "just import everything" seem to go against the design philosophy of Python, and instead, I am supposed to only import what I really need.

My question now is, how should I structure such common class definitions so it "makes sense" in a Python package?

What I have tried so far

One class per file

This most closely mimics the "one class per file" convention in C#, leading to a directory tree as follows:

main.py
mylib/
    __init__.py
    common/
        User.py
        Employee.py
        Customer.py
    controller/
        ...
    ...

Back in the main.py file, I would write something like this:

from mylib.common.User import User;
from mylib.common.Employee import Employee;
from mylib.common.Customer import Customer;

This works, but it seems like it has a lot of verbosity that it really doesn't need.

All classes in one file

This seems to work better with the import system as I have understood it. Instead of putting every class into its own file, I would instead put every class into one file. The file structure would then look like this:

main.py
mylib/
    __init__.py
    common.py
    controller/
        ...
    ...

Back in the main.py file, I would write something like this:

from mylib.common import User, Employee, Customer;

This seems much more succinct, but I feel like with a bigger project, this could mean a lot of class definitions in one file, and possibly lead to common.py becoming a bloated mess, containing a lot of classes that don't really have anything to do with each other.

Aucun commentaire:

Enregistrer un commentaire