DEV Community

Discussion on: Using Python's Type Annotations

Collapse
 
dwd profile image
Dave Cridland

Actually it's much cleverer than having a comment:

  • Your IDE can pick up the difference much more easily and warn you, plus the typing information itself is syntax-checked.
  • Tools (like MyPy) can enforce it.
  • Yes, it can be ignored or overridden by a developer - that could be useful inside library internals.
  • User-defined metatypes, like the UserId example given in the docs, aren't possible with your comments.

For an example of the latter point:

from typing import NewType

UserId = NewType('UserId', int)
user1 = UserId(1)
user2 = UserId(2)

# user1 and user2 are simply integer values, but with typing info.

user = get_user(user1) # OK
user = get_user(user2) # OK
user3 = user1 + user2 # OK, these are ints!
user = get_user(user3) # Not OK! That's not a UserId