Why no ‘const’ in Python? [closed]

C and Python belongs to two different classes of languages.

The former one is statically typed. The latter is dynamic.

In a statically typed language, the type checker is able to infer the type of each expression and check if this match the given declaration during the “compilation” phase.

In a dynamically typed language, the required type information is not available until run-time. And the type of an expression may vary from one run to an other. Of course, you could add type checking during program execution. This is not the choice made in Python. This has for advantage to allow “duck typing”. The drawback is the interpreter is not able to check for type correctness.

Concerning the const keyword. This is a type modifier. Restricting the allowed use of a variable (and sometime modifying allowed compiler optimization). It seems quite inefficient to check that at run-time for a dynamic language. At first analysis, that would imply to check if a variable is const or not for each affectation. This could be optimized, but even so, does it worth the benefit?

Beyond technical aspects, don’t forget that each language has its own philosophy. In Python the usual choice is to favor “convention” instead of “restriction”. As an example, constant should be spelled in all caps. There is no technical enforcement of that. It is just a convention. If you follow it, your program will behave as expected by “other programmers”. If you decide to modify a “constant”, Python won’t complain. But you should feel like your are doing “something wrong”. You break a convention. Maybe you have your reasons for doing so. Maybe you shouldn’t have. Your responsibility.

As a final note, in dynamic languages, the “correctness” of a program is much more of the responsibility of your unit testings, than in the hand of the compiler. If you really have difficulties to made the step, you will find around some “code checkers”. Those are PyLint, PyChecker, PyFlakes…

Leave a Comment