0

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 ?

martineau
  • 112,593
  • 23
  • 157
  • 280
Peter Moore
  • 1,387
  • 10
  • 25
  • 2
    It's a type hint. Per [PEP 526](https://www.python.org/dev/peps/pep-0526/), "Type annotation can be added to an assignment statement or to a single expression indicating the desired type of the annotation target to a third party type checker" – Brian Jun 15 '20 at 22:10
  • 1
    Type hints != type checking. It's just a _hint_. – ggorlen Jun 15 '20 at 22:12
  • https://docs.python.org/3/library/typing.html – Sean Breckenridge Jun 15 '20 at 22:12

1 Answers1

1

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
James McGuigan
  • 6,794
  • 4
  • 23
  • 25