In my code either of the above two options would work equally well but I am interested in finding out the pros and cons of both approaches.
It honestly depends on your needs. Most of the time a module of functions will be what you’re looking for.
Python classes (imho) shouldn’t be thought of like classes in C# or C++ or Java, there needs to be a logical reason to group a set of functions into a larger parent, data structures would be a good example of this, you want a congruent set of functions that apply directly to the class instead of a loosely collected set of functions that are general purpose.
- Module of Functions: general purpose, utility, and more “global” functions
- Module of Class of Functions: grouped classes of similar needs, different linked list data types or audio processing functions or different tree types.
A module is for the overall hierarchical grouping of similar systems, I usually have all utility functions under a single module, all data under another, my data layer and connectors under a more “parent” type module. Since a module is just a mental grouping it’s less about what types of systems are in it (classes or functions, honestly probably a mix of the two) and more about the logical connections between the systems under the module.
1
The basic question is if you need to have different instances of your module/class. a python module is like a singleton – you refer always to the same object, i.e. if you need instances, you need a class.
However, if you do not need instances you might still have the need to set up your “object” to an initial state. while this is clearly possible with a plain module, if the initializing is more complex than just setting some values, I would advice to have initializing code in a class’s __init__
method for readability.
3