Python Type Hints: Code readability perspective

Arvind Suthar
1 min readJul 11, 2023

--

This article is a quick introduction to type hints for beginners who’ve started programming in Python. If you’re an experienced programmer, then I suggest checking out more advanced articles or documentation.

Python is a dynamic language, where data/variable types aren’t generally defined. This makes Python flexible and convenient for developers because you don’t have to rigorously define and track variable types.

When we’re reading code base of bigger projects, especially libraries, “Type Hints” help us to know which object types are associated with which variables. If you’re coming from a statically typed languages(C/C++, Java, TypeScript, etc), then you’ll already be familiar with type declarations and you know its importance while debugging or understanding code base.

With Python 3.5, type hints officially became part of the language.

Type hinting is a formal solution to statically indicate the type of a value.

Syntax of Python Type Hints

Type hints involve a color and a type declaration after the first invocation/declaration of a variable.

name: str
age: int

name = input("Enter your name: ")
age = int(input("Enter your age: "))

Type hinting Python functions

Type hints can be implemented in Python functions to document the values they accept and return.

greeting = "Hello, {}, you're {} years old"

def greet(user:str, age:int) -> str:
return greeting.format(user, age)

name = input("Enter your name: ")
age = int(input("Enter your age: "))
python
print(greet(name, age))

Similarly, you can apply type hints to container objects, classes, etc. Check out following sources to take a deep dive into type hints in Python:

--

--

Arvind Suthar
Arvind Suthar

Written by Arvind Suthar

0 Followers

Backend Engineering

No responses yet