/ home / Programming / Python /

'const'

Const basically makes data "Read-Only". Its an important feature to help prevent developers from changing data they were not supposed to, and to informing other developers that data marked const will not change.

Python Qt/Cpp
  1. Python 3.10.5 (main, Jun 6 2022, 18:49:26) [GCC 12.1.0] on linux
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> from typing import Final
  4. >>> sneed: Final = "feed"
  5. >>> sneed
  6. 'feed'
  7. >>> sneed = "seed"
  8. >>> sneed
  9. 'seed'
  1. const QString sneed("feed"); // west const // Start reading here
  2. sneed = "seed"; // Will not compile
  3. QString const chuck("seed"); // east const
  4. chuck = "feed"; // Will not compile
  5. /* <Kill-Animals> I forget; is there any difference between these two statements: `const QString foo("foo"); QString const bar("bar");`
  6. * <kalven> no
  7. * <Kill-Animals> Ah okay, Are there people who put const afterwards? It just looks weird.
  8. * <kalven> yes, we call them weirdos
  9. * <great_taste> some people are weird, yes
  10. * <kalven> this is colloquially referred to as "west const" and "east const" */

Read as:
  • [ Something identified as ] 'sneed' [which may or may not already exist]
  • finally [ but not really finally ] equals "feed" [ implying that sneed is a string type ].
  • A [ new ] constant string 'sneed'
  • is [ initialized as ] "feed".

Benefits:
  • mypy will tell you that this variable 'shouldnt' be reassigned.
  • Code can not be compiled if you try to overwrite sneed.
  • Standard practice.
  • Part of the language.

Drawbacks:
  • You have to install mypy.
  • Variable is not readonly.
  • `sneed: Final = "feed"` can colliqually referred to as an "east const".
  • Not standard practice.
  • Not part of the language.
  • None.

Final Thoughts