/ 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. # Special thanks from jinsuun__ on #python irc
  2. from dataclasses import dataclass
  3. @dataclass
  4. class C:
  5. m_c: int
  6. isLetter : bool = False
  7. isNonCharacter : bool = False
  8. isNull : bool = False
  9. isNumber : bool = False
  10. isPrintable : bool = True
  11. isSpace : bool = False
  12. isUpper : bool = False
  13. n = 88
  14. c = C(n)
  15. match c:
  16. case C(0):
  17. c.isNull = True
  18. case C( m_c = x ) if x in range( 1, 32 ) or x == 127:
  19. c.isNonCharacter = True
  20. c.isPrintable = False
  21. case C(" "):
  22. c.isSpace = True
  23. case C(x) if x in range( ord("A"), ord("Z") + 1 ):
  24. c.isUpper = True
  25. c.isLetter = True
  26. case C(x) if x in range( ord("a"), ord("z") + 1 ):
  27. c.isUpper = False
  28. c.isLetter = True
  29. case C(x) if x in range( ord("0"), ord("9") + 1 ):
  30. c.isNumber = True
  31. case _:
  32. pass
  1. qint8 c(88);
  2. bool isLetter (false);
  3. bool isNonCharacter(false);
  4. bool isNull (false);
  5. bool isNumber (false);
  6. bool isPrintable (true );
  7. bool isSpace (false);
  8. bool isUpper (false);
  9. switch (c) {
  10. default: break;
  11. case 0 :
  12. isNull = true;
  13. [[fallthrough]];
  14. case 1 ... 31:
  15. case 127 : // Delete
  16. isNonCharacter = true;
  17. isPrintable = false;
  18. break;
  19. case ' ':
  20. isSpace = true;
  21. break;
  22. case 'A' ... 'Z':
  23. isUpper = true;
  24. [[fallthrough]];
  25. case 'a' ... 'z':
  26. isLetter = true;
  27. break;
  28. case '0' ... '9':
  29. isNumber = true;
  30. break;
  31. }

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