4
$\begingroup$

A lot of languages have some form of constant variables - hell, even JavaScript has them.

Yet Python doesn't. What possible benefits does this have for the Python language?

$\endgroup$
1
  • $\begingroup$ My biggest pet peeve with Python & Lua actually $\endgroup$
    – CPlus
    May 18, 2023 at 6:46

2 Answers 2

10
$\begingroup$

I'm not sure that Python specifically doesn't have them because of any concrete advantages to not having them. That is, there may be such advantages (one is discussed in mousetail's answer), but I don't think these advantages are what motivated Python's design decision in this case.

I suspect the main reason Python doesn't have them is simply because constants aren't needed to do anything new; any program which uses constants can be written without them, and will have the same behaviour (barring pathological cases where a program intentionally tries to assign to a constant and then catch the exception at runtime). Like access modifiers and type annotations, they can be used to check the correctness of a program but they don't change the program's behaviour, so many dynamic languages including Python and its contemporaries either don't have them, or added them significantly later (like const was eventually added to Javascript).

This is similar to the principle that "we're all consenting adults", which is a part of Python's design philosophy: the language itself doesn't need to stop you from doing things that you don't want to do. This principle can certainly be criticised, and many other languages don't adopt it, but for better or worse it is something that Python's design is based on.

$\endgroup$
9
$\begingroup$

Monkey Patching

A core feature of Python is that absolutely everything is accessible and modifiable. Even things like closure bound variables, which are still truly private even in JavaScript, are accessible and mutable in python.

A major benefit of this system is you can modify the behavior of any code, even code inside third party modules or constants there in. This functionally is used extensively for things like unit testing when you may want to isolate some functionality but control the rest. Everything being mutable allows you to do that

If Python added constant variables, it would mean some things would not be patch-able like is conventional in Python, removing a major benefit from Python.

Similar to how private variables are marked with _ in Python, constants are marked with ALL_CAPS. It's up to the programmer to choose to actually not modify them or not.

Also Python doesn't have variable declarations at all so it would be a much bigger step to add them, compared to JavaScript which already had var when const was introduced.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .