0

Very recently I have seen something like this in Python:

const: str = 5;

I thought it would give an error, since one is assigning a numerical value to a string declared constant; however, when I print const+5, hopping for another error, it gives me 10, as if const was a numerical constant.

What's happening here?

  • 6
    `const` is just the variable name, it is not the same as the `const` keyword in C++ (or in other languages that have it) that prevents modification of the var's value. `str` is the type hint: [What are type hints in Python 3.5?](https://stackoverflow.com/q/32557920/2745495) (which is a pretty bad type hint in your example) – Gino Mempin Feb 17 '22 at 00:24
  • 4
    Whoever wrote the code you saw is not your friend. Don't trust anything they tell you. – Samwise Feb 17 '22 at 00:36

1 Answers1

2

There are two things to understand here:

  1. const has no special meaning in Python. Here it's just being used as a variable name (which is somewhat evil, since it can only be intended to confuse the unwary).
  2. Type annotations are not enforced by the Python interpreter. Assigning an incompatible type will, however, produce an error if you run a static typechecker on your code:
test.py:1: error: Incompatible types in assignment (expression has type "int", variable has type "str")

Also, note that semicolons are not required in Python, and are generally considered bad style.

Samwise
  • 68,105
  • 3
  • 30
  • 44