November 02, 2021

What Python can learn from C

 

The Python language has become famous because of its object oriented features. This was the main improvement over previous scripting languages like Perl. On the other hand Python has a seldom described features which can be used as a replacement to classes. The concept of a module is to put all the functions in a single file and include this file somewhere else.
Somebody may argue, that a class should be stored in a file and including a module is equal to include a class. The situation is more complicated. Because modules can be used without classes. This programming style is what c programmers are doing: they are creating modules in which the scope of variables and functions is limited and then the module gets included into the main program.
Apart from modules Python support also packages. A package is a directory which contains of many modules. This allows to create larger programs and very important they can be converted easily into c code. That means the original Python program doesn't use classes there for the similarity with plain C is bigger.
The real problem in programming is not to learn a certain language but the problem has how to write programs which are larger than 100 lines of code. The amount of 100 LoC fits well into a single file. It is equal to define a small number of variables and apply 4-5 functions to them. The problem is that real programs will need much more code lines and hundreds of functions. Organizing them into a single file is technically possible but it will become unlikely that the programmer is able to maintain such a file. Object oriented programming provides one possible answer to this problem, but modular programming has also an answer.
Let us describe how to write a module in Python without using classes. The idea is to create a new file and import this file in the main program. The new file contains of variables similar to class variables and methods which can modify these variables. Some of the functions can be accessed from the outside so that the module communicates with the main program. In contrast to the C language the workflow was simplified drastically, there is no need to create dedicated header files and the program will run without a compilation step.