Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign a number to a string constant in python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading