Type hints in Python

In the Barry book (Head First Python, 2nd edition), he always includes something known as “type hints” in his code. This is akin to making a note that a particular variable is intended to be a string, an integer, a Boolean value, etc.

Every time Barry specifies a variable type like so:

def greeting(name: str) -> str:
  return 'Hello, ' + name

You can OMIT the boldfaced parts. Those are the markup for type hints, and hardly anyone uses them in Python.

This works perfectly well (and is so much nicer):

def greeting(name):
  return 'Hello, ' + name

The version with no type hints is what you have learned up until now, and there’s nothing wrong with using it.

Type hints are completely unnecessary:

“This PEP introduces a provisional module to provide these standard definitions and tools, along with some conventions for situations where annotations are not available.”

“While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime.”

See also this Reddit post for more about how type hints are not needed and also not standard practice in Python.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.