Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

choosing between Modules and Classes

Tags:

In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:

  1. Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing something in clarity of my code.

  2. Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.

EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.

like image 787
Xolve Avatar asked Mar 01 '09 18:03

Xolve


People also ask

What is the difference between modules and classes?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

Should I use class or module?

The difference between a class and a module in python is that a class is used to define a blueprint for a given object, whereas a module is used to reuse a given piece of code inside another program.

Why are classes better than functions?

Classes provide a way to merge together some data and related operations. If you have only one operation on the data then using a function and passing the data as argument you will obtain an equivalent behaviour, with less complex code.

Why do we use modules in class?

Modules allow instructors to organize content to help control the flow of the course. Modules are used to organize course content by weeks, units, or a different organizational structure.


1 Answers

Sounds like the classic conundrum :-).

In Python, there's nothing dirty or shameful about choosing to use a module if that's the best approach. After all, modules, functions, and the like are, in fact, first-class citizens in the language, and offer introspection and properties that many other programming languages offer only by the use of objects.

The way you've described your options, it kinda sounds like you're not too crazy about a class-based approach in this case.

I don't know if you've used the Django framework, but if not, have a look at the documentation on how it handle settings. These are app-wide, they are defined in a module, and they are available globally. The way it parses the options and expose them globally is quite elegant, and you may find such an approach inspiring for your needs.

like image 200
Jarret Hardie Avatar answered Sep 28 '22 02:09

Jarret Hardie