Type Hints in Python
Anirudh Menon
Contents
 Introduction to Type Checking and Type hints
 Why Type Hints? What it is and what it isn’t?
 How to type hint in python?
 Typing examples
 Structural Subtyping (PEP544)
 Protocol example
 References
Introduction
Type Checking and Type Hints
Type Checking
 Type checking is the process of verifying the type safety of a program.
 Type checker - Tool to check if the right type and number of arguments are passed.
 Type checking may happen at compile time or at run time.
 In Python,
Type Hints
 Formalized in PEP484(introduce a gradual type system) and other PEPs
 Supported by the typing module of python(3.5 and later).
 PEP484 aims to provide a standard syntax for type annotations,
 Opens Python code to easier static analysis
def hello(name='nobody’):
''' Say hello to a person
:param: string value
:return: string value
'’’
return 'Hello' + name
def hello(name: str = 'nobody’) -> str:
''' Say hello to a person
'''
return 'Hello' + name
Why?
 Type hints catches (certain) bugs earlier
 Refactoring and update with confidence
 Improve code readability (Code as documentation)
 Type checkers can be easily integrated with CI tools.
 Make IDEs work better (if you use one!) - code generation
utilizing type information.
What it is not…
 It’s not going to fix all code issues
 It does not about do runtime type checking,
hence no performance overhead at runtime.
 It’s not going to make Python a static-typed language
Type hints are optional, python follows gradual typing.
 It does not enhance performance.
(type annotations can in theory be used to optimize
generated code, but these aren’t done in python
as of today)
Type Checkers
 Popular Static Type Checkers in Python: Mypy(Python Community), Pyright(Microsoft),
Pyre(Facebook), Pytype(Google)
 Annotations are added to python code to annotate type hints.
 Python interpreter does not automatically conduct any type checking whatsoever. That means
those annotations have no effects during runtime, even if you are trying to pass a wrong type for
an object to a function.
 Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic
(or 'duck') typing and static typing.
mypy
 Work on mypy began in 2012, a static type checker for python.
 It combines the benefits of dynamic (or 'duck') typing and static typing
that is, it support gradual typing.
 Install mypy type checker:
 Usage:
 To avoid individual lines from being flagged add the comment:
pip install mypy
mypy [--strict|--disallow-untyped-defs] <python_script>
# type: ignore
How do we do it in python?
(demo/examples)
 The old way - Using type comments.. (python 2)
 Using type annotations (using typing) –
 For that install “typing”,
In Python 3.5 and higher:
>>> import typing
In Python 3.2–3.4, you need to install it before importing:
$ pip install typing
How to type hint?
def add(a, b): # type: (float, float) -> float
return a + b
def add(a: float, b: float) -> float:
return a + b
Annotations
 Function argument/return type annotations
 Variable Annotations
>>> x: int = …
 Special Forms - can be used as types in annotations using []
Tuple type (E.g.: Tuple[X, Y])
Union type (E.g.: Union[X, Y]) - means either X or Y
Optional type – equivalent to Union[X, None]
Callable type (E.g.: Callable[[int], str] is a function of (int) -> str)
 Many more – Literal, Final, Annotated, etc.
 Functions and decorators – cast, overload, final, no_type_check, type_check_only, etc.
 Constant - TYPE_CHECKING
Python will remain a dynamically
typed language, and the authors have
no desire to ever make type hints
mandatory, even by convention.
-
Guido van Rossum, Jukka Lehtosalo,
and Łukasz Langa,
PEP 484—Type Hints
Typing examples
Examples
Optional
“Be liberal in what you accept, and conservative in what you return”
Examples
Union and overload
PEP544
 PEP 544 introduced Structural subtyping (static duck typing)
 Protocols - types supporting structural subtyping.
 Nominal subtyping is strictly based on the class hierarchy. This is the default in mypy and it
matches how the native isinstance check works.
 Structural subtyping can be implemented with protocol. Class D is a structural subtype of
class C if the former has all attributes and methods of the latter, and with compatible types.
 Structural subtyping can be seen as a static equivalent of duck typing.
Predefined Protocols
 PEP484 and typing module defines abstract base classes for several common Python protocols
such as Iterable and Sized.
 ABCs in typing module already provide structural behavior at
runtime, isinstance(Bucket(), Iterable) returns True.
Cons of this..
 They must be explicitly subclassed or registered.
 This is particularly difficult to do with library types as the type objects may be hidden deep in the
implementation of the library.
 Also, extensive use of ABCs might impose additional runtime costs.
 PEP544 solves these problems by allowing users to write the code without explicit base classes in
the class definition.
Protocol based implementation
 After PEP544 structural subtyping:
(the above example is from PEP544)
Structural SubTyping
 Structural subtyping is natural for Python programmers since it matches the runtime semantics of
duck typing
 PEP544 says - Protocol classes are specified to complement Normal classes and users are free to
choose where to apply a particular solution.
Examples
A parameterized generic is a generic type, written as list[T], where T is a type variable
that will be bound to a specific type with each usage.
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar(‘T’)
def sample(population: Sequence[T], size: int) -> list[T]:
…
“bound” in TypeVar is used to set the upper bound
for acceptable types.
References
 typing module docs
 PEP 484, PEP 544 and others.
 Why is Python a dynamic language and also a strongly typed language?
 Slide decks by Luciano Ramalho and Guido van Rossum.
 David’s tweet 
Thank You
Type Hints in Python
Anirudh Menon
Type hints are the biggest change in the history of Python since the unification of types and classes in
Python 2.2, released in 2001. However, type hints do not benefit all Python users equally. That’s why
they should always be optional.
- Luciano Ramalho
Author of Fluent Python

More Related Content

PPTX
Python basics
PDF
Introduction to Python
PDF
Lesson 03 python statement, indentation and comments
PPT
Unit I Advanced Java Programming Course
PPTX
Loops in Python
PPTX
Print input-presentation
PPTX
Values and Data types in python
PPTX
Angular Lazy Loading and Resolve (Route Resolver)
Python basics
Introduction to Python
Lesson 03 python statement, indentation and comments
Unit I Advanced Java Programming Course
Loops in Python
Print input-presentation
Values and Data types in python
Angular Lazy Loading and Resolve (Route Resolver)

What's hot (20)

PDF
How to start using types in Python with mypy
PPT
Python List.ppt
PPT
Wrapper class (130240116056)
PPTX
OOP Unit 1 - Foundation of Object- Oriented Programming
PPT
Pattern matching
PDF
What is Python JSON | Edureka
PPT
Looping statements in Java
PPTX
python presentation
PPTX
Decision making &_loops_in_python
PPTX
Python-Functions.pptx
PPTX
Finaal application on regular expression
PDF
Let’s Learn Python An introduction to Python
PPTX
Python programming
PPTX
Regular Expression (Regex) Fundamentals
PPTX
Unit 1 OOSE
PDF
Python - code quality and production monitoring
PPTX
Python: Polymorphism
PDF
Python-02| Input, Output & Import
PDF
Scientific Computing with Python - NumPy | WeiYuan
PDF
A deep dive into libuv
How to start using types in Python with mypy
Python List.ppt
Wrapper class (130240116056)
OOP Unit 1 - Foundation of Object- Oriented Programming
Pattern matching
What is Python JSON | Edureka
Looping statements in Java
python presentation
Decision making &_loops_in_python
Python-Functions.pptx
Finaal application on regular expression
Let’s Learn Python An introduction to Python
Python programming
Regular Expression (Regex) Fundamentals
Unit 1 OOSE
Python - code quality and production monitoring
Python: Polymorphism
Python-02| Input, Output & Import
Scientific Computing with Python - NumPy | WeiYuan
A deep dive into libuv
Ad

Similar to Type hints in python & mypy (20)

PDF
型ヒントについて考えよう!
PDF
The Benefits of Type Hints
PDF
Enjoy Type Hints and its benefits
PPTX
Type Annotations in Python: Whats, Whys and Wows!
PDF
Python typing module
PDF
Static type checking in python
PDF
David Mertz. Type Annotations. PyCon Belarus 2015
PDF
Type Checking in Python at Tiqets
KEY
Mypy pycon-fi-2012
PDF
Tip Top Typing - A Look at Python Typing
PDF
Python types and doctests by Lauri Kainulainen
PDF
Types my way: Static Typing in Python
PPTX
Python 3.6 Features 20161207
ODP
Dynamic Python
PDF
Intro python-object-protocol
PDF
What is new in Python 3.9
PDF
E-Notes_3720_Content_Document_20250107032323PM.pdf
PDF
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
PDF
Datatypes in Python.pdf
PDF
The two flavors of Python 3.13 - PyHEP 2024
型ヒントについて考えよう!
The Benefits of Type Hints
Enjoy Type Hints and its benefits
Type Annotations in Python: Whats, Whys and Wows!
Python typing module
Static type checking in python
David Mertz. Type Annotations. PyCon Belarus 2015
Type Checking in Python at Tiqets
Mypy pycon-fi-2012
Tip Top Typing - A Look at Python Typing
Python types and doctests by Lauri Kainulainen
Types my way: Static Typing in Python
Python 3.6 Features 20161207
Dynamic Python
Intro python-object-protocol
What is new in Python 3.9
E-Notes_3720_Content_Document_20250107032323PM.pdf
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
Datatypes in Python.pdf
The two flavors of Python 3.13 - PyHEP 2024
Ad

Recently uploaded (20)

PDF
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
PDF
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
PDF
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
PDF
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
PDF
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
PDF
Data Virtualization in Action: Scaling APIs and Apps with FME
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
PDF
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
PPTX
Training Program for knowledge in solar cell and solar industry
PPTX
Module 1 Introduction to Web Programming .pptx
PDF
LMS bot: enhanced learning management systems for improved student learning e...
PDF
Ensemble model-based arrhythmia classification with local interpretable model...
PDF
SaaS reusability assessment using machine learning techniques
PPTX
Build automations faster and more reliably with UiPath ScreenPlay
PDF
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
PDF
giants, standing on the shoulders of - by Daniel Stenberg
PDF
Auditboard EB SOX Playbook 2023 edition.
PDF
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
PDF
Co-training pseudo-labeling for text classification with support vector machi...
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
Data Virtualization in Action: Scaling APIs and Apps with FME
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
Training Program for knowledge in solar cell and solar industry
Module 1 Introduction to Web Programming .pptx
LMS bot: enhanced learning management systems for improved student learning e...
Ensemble model-based arrhythmia classification with local interpretable model...
SaaS reusability assessment using machine learning techniques
Build automations faster and more reliably with UiPath ScreenPlay
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
giants, standing on the shoulders of - by Daniel Stenberg
Auditboard EB SOX Playbook 2023 edition.
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
Co-training pseudo-labeling for text classification with support vector machi...

Type hints in python & mypy

  • 1. Type Hints in Python Anirudh Menon
  • 2. Contents  Introduction to Type Checking and Type hints  Why Type Hints? What it is and what it isn’t?  How to type hint in python?  Typing examples  Structural Subtyping (PEP544)  Protocol example  References
  • 4. Type Checking  Type checking is the process of verifying the type safety of a program.  Type checker - Tool to check if the right type and number of arguments are passed.  Type checking may happen at compile time or at run time.  In Python,
  • 5. Type Hints  Formalized in PEP484(introduce a gradual type system) and other PEPs  Supported by the typing module of python(3.5 and later).  PEP484 aims to provide a standard syntax for type annotations,  Opens Python code to easier static analysis def hello(name='nobody’): ''' Say hello to a person :param: string value :return: string value '’’ return 'Hello' + name def hello(name: str = 'nobody’) -> str: ''' Say hello to a person ''' return 'Hello' + name
  • 6. Why?  Type hints catches (certain) bugs earlier  Refactoring and update with confidence  Improve code readability (Code as documentation)  Type checkers can be easily integrated with CI tools.  Make IDEs work better (if you use one!) - code generation utilizing type information.
  • 7. What it is not…  It’s not going to fix all code issues  It does not about do runtime type checking, hence no performance overhead at runtime.  It’s not going to make Python a static-typed language Type hints are optional, python follows gradual typing.  It does not enhance performance. (type annotations can in theory be used to optimize generated code, but these aren’t done in python as of today)
  • 8. Type Checkers  Popular Static Type Checkers in Python: Mypy(Python Community), Pyright(Microsoft), Pyre(Facebook), Pytype(Google)  Annotations are added to python code to annotate type hints.  Python interpreter does not automatically conduct any type checking whatsoever. That means those annotations have no effects during runtime, even if you are trying to pass a wrong type for an object to a function.  Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or 'duck') typing and static typing.
  • 9. mypy  Work on mypy began in 2012, a static type checker for python.  It combines the benefits of dynamic (or 'duck') typing and static typing that is, it support gradual typing.  Install mypy type checker:  Usage:  To avoid individual lines from being flagged add the comment: pip install mypy mypy [--strict|--disallow-untyped-defs] <python_script> # type: ignore
  • 10. How do we do it in python? (demo/examples)
  • 11.  The old way - Using type comments.. (python 2)  Using type annotations (using typing) –  For that install “typing”, In Python 3.5 and higher: >>> import typing In Python 3.2–3.4, you need to install it before importing: $ pip install typing How to type hint? def add(a, b): # type: (float, float) -> float return a + b def add(a: float, b: float) -> float: return a + b
  • 12. Annotations  Function argument/return type annotations  Variable Annotations >>> x: int = …  Special Forms - can be used as types in annotations using [] Tuple type (E.g.: Tuple[X, Y]) Union type (E.g.: Union[X, Y]) - means either X or Y Optional type – equivalent to Union[X, None] Callable type (E.g.: Callable[[int], str] is a function of (int) -> str)  Many more – Literal, Final, Annotated, etc.  Functions and decorators – cast, overload, final, no_type_check, type_check_only, etc.  Constant - TYPE_CHECKING
  • 13. Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention. - Guido van Rossum, Jukka Lehtosalo, and Łukasz Langa, PEP 484—Type Hints
  • 15. Examples Optional “Be liberal in what you accept, and conservative in what you return”
  • 17. PEP544  PEP 544 introduced Structural subtyping (static duck typing)  Protocols - types supporting structural subtyping.  Nominal subtyping is strictly based on the class hierarchy. This is the default in mypy and it matches how the native isinstance check works.  Structural subtyping can be implemented with protocol. Class D is a structural subtype of class C if the former has all attributes and methods of the latter, and with compatible types.  Structural subtyping can be seen as a static equivalent of duck typing.
  • 18. Predefined Protocols  PEP484 and typing module defines abstract base classes for several common Python protocols such as Iterable and Sized.  ABCs in typing module already provide structural behavior at runtime, isinstance(Bucket(), Iterable) returns True.
  • 19. Cons of this..  They must be explicitly subclassed or registered.  This is particularly difficult to do with library types as the type objects may be hidden deep in the implementation of the library.  Also, extensive use of ABCs might impose additional runtime costs.  PEP544 solves these problems by allowing users to write the code without explicit base classes in the class definition.
  • 20. Protocol based implementation  After PEP544 structural subtyping: (the above example is from PEP544)
  • 21. Structural SubTyping  Structural subtyping is natural for Python programmers since it matches the runtime semantics of duck typing  PEP544 says - Protocol classes are specified to complement Normal classes and users are free to choose where to apply a particular solution.
  • 22. Examples A parameterized generic is a generic type, written as list[T], where T is a type variable that will be bound to a specific type with each usage. from collections.abc import Sequence from typing import TypeVar T = TypeVar(‘T’) def sample(population: Sequence[T], size: int) -> list[T]: … “bound” in TypeVar is used to set the upper bound for acceptable types.
  • 23. References  typing module docs  PEP 484, PEP 544 and others.  Why is Python a dynamic language and also a strongly typed language?  Slide decks by Luciano Ramalho and Guido van Rossum.  David’s tweet 
  • 24. Thank You Type Hints in Python Anirudh Menon
  • 25. Type hints are the biggest change in the history of Python since the unification of types and classes in Python 2.2, released in 2001. However, type hints do not benefit all Python users equally. That’s why they should always be optional. - Luciano Ramalho Author of Fluent Python