SlideShare a Scribd company logo
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

PDF
How to start using types in Python with mypy
PPTX
Python
PDF
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
PDF
Django Tutorial | Django Web Development With Python | Django Training and Ce...
PDF
Data visualization in Python
PPTX
Python Scipy Numpy
PPTX
Dictionaries and Sets in Python
PDF
PyTorch 2 Internals
How to start using types in Python with mypy
Python
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Data visualization in Python
Python Scipy Numpy
Dictionaries and Sets in Python
PyTorch 2 Internals

What's hot (20)

PDF
Django Introduction & Tutorial
PPTX
PPTX
Programacion orientada a objetos en javascript
PDF
Python Interview Questions And Answers
PDF
Python Basics | Python Tutorial | Edureka
PPTX
PPT
PYTHON - TKINTER - GUI - PART 1.ppt
PPTX
NumPy.pptx
PPTX
Pytorch
PDF
RDM 2020: Python, Numpy, and Pandas
PDF
PHP Basic & Variables
PDF
Python - object oriented
PDF
Python Advanced – Building on the foundation
PDF
Python strings
PPTX
Introduction to-python
PPTX
Programming
PPTX
NumPy.pptx
PPTX
Python Basics
PDF
Orientação a Objetos em Python
PPT
python.ppt
Django Introduction & Tutorial
Programacion orientada a objetos en javascript
Python Interview Questions And Answers
Python Basics | Python Tutorial | Edureka
PYTHON - TKINTER - GUI - PART 1.ppt
NumPy.pptx
Pytorch
RDM 2020: Python, Numpy, and Pandas
PHP Basic & Variables
Python - object oriented
Python Advanced – Building on the foundation
Python strings
Introduction to-python
Programming
NumPy.pptx
Python Basics
Orientação a Objetos em Python
python.ppt
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
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
sap open course for s4hana steps from ECC to s4
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
Assigned Numbers - 2025 - Bluetooth® Document
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Spectroscopy.pptx food analysis technology
Building Integrated photovoltaic BIPV_UPV.pdf
MYSQL Presentation for SQL database connectivity
A comparative analysis of optical character recognition models for extracting...
Per capita expenditure prediction using model stacking based on satellite ima...
Dropbox Q2 2025 Financial Results & Investor Presentation
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Empathic Computing: Creating Shared Understanding
sap open course for s4hana steps from ECC to s4
NewMind AI Weekly Chronicles - August'25-Week II
“AI and Expert System Decision Support & Business Intelligence Systems”
gpt5_lecture_notes_comprehensive_20250812015547.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?

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