1

Why is code like this apparently legal (does not give a syntax error when running) in Python 3?

wut:2+2=5

I've tried to find out what this type of syntax could mean and I could not find it. It seems like a key-value pair, but can you just have one lying around? And "2+2=5" is not a valid... anything, is it?

  • 1
    [Type hints](https://docs.python.org/3/library/typing.html): it treats `2+2` as a type hint, even though it appears to be meaningless. – Warren Weckesser Aug 04 '20 at 16:58

1 Answers1

0

They are type hints in python. Basically, you hint the type of the object(s) you're using. Type-hints are for maintainability and don't get interpreted by Python. So, you might say that a variable has type float whereas python will internally interpret as int only. Eg -

my_var:float = 4
print(type(my_var))

OUTPUT :

<class 'int'>

In your case, it doesn't make much sense. But to ease maintainability when your projects grow large, it is helpful. These can be considered as the next step from # type comments. Eg-

  1. my_var = 4.2  # type: float
    
  2. my_var: float = 4.2
    

The above two codes can be considered to be similar in their functionalities.

You can read more about it here - https://docs.python.org/3/library/typing.html

More on this - What are type hints in Python 3.5?

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32