A typo revealed a statement I don't understand. Can someone explain what the purpose of the colon is in this context?
>>> test : 'what does this do?'
I thought it might be an implicit dict like the implicit tuple
>>> 1,2
(1, 2)
But does not return anything. So I started to mess with it and found an error.
>>> True : 'fs'
File "<stdin>", line 1
SyntaxError: illegal target for annotation
So I looked up that error to find PEP 526 which I don't understand either :-)
>>> xx : int
>>> xx = 'sdfs'
>>> xx
'sdfs'
I mean its not type checking as I'm able to assign a string. Can someone please help me understand this ?
These are python type hints.
As python is a dynamically typed language (unlike say Java), these are not enforced at runtime. However, they act as an extra level of documentation. Your linter (such as pylint) can use them to warn when you have passed a string into a function that was expecting an int. Also your IDE can use them for enhanced autocompletion.
A couple of packages that help you make better use of type hints:
The purpose of string type hints is a workaround to circular dependencies.
Parent.py
from .Parent import Parent
class Child(Parent):
parent: Parent
pass
Parent.py
# from .Child import Child # This would cause a circular dependency
class Parent:
child: 'Child' # String type hint required as Child cannot be imported
pass