How to start using types in
Python with Mypy
Carlos
Villavicencio
Ecuadorian 󰎸
Software Developer at Stack Builders
Community leader
Amateur photographer
cvillavicencio cvillavicencio@stackbuilders.com
@po5i
po5i
Quilotoa Lake, Ecuador 2020.
大家好!
Types and
Python
Data Structures
Primitive Non-primitive
Integer Float String Boolean Array List Tuple Dictionary Set File
Linear Non-linear
Stacks Queues Graphs Trees
How to start using types in Python with mypy
How to start using types in Python with mypy
Types are known in compilation time
Variables bind to types
Very verbose
Bytecode is well optimized in memory
Types are known in runtime
Variables bind to objects 🦆
Less verbose
Bugs in run-time are very common
Dynamic vs. Static Languages
Weakly vs. Strongly Type System
Implicit coercion between non-related types
Flexibles
Unpredictables
Explicit type conversion (casting)
Strict rules on the static analysis.
Type Safety
Static type checking
in Python
But you can also use
Type
Annotations
meat: str = "Beef"
weight_pounds: float = "0.5"
# mypy
# error: Incompatible types in assignment
# (expression has type "str", variable has type "float")
Primitive types 🦕
Let’s prepare some 🍔
def make_hamburger(meat, number_of_meats):
return ["bread"] + [meat] * number_of_meats + ["bread"]
print(make_hamburger("BEEF", 2))
# ['bread', 'BEEF', 'BEEF', 'bread']
class MyTest(unittest.TestCase):
def test_make_hamburger_returns_list(self):
self.assertTrue(isinstance(make_hamburger("beef", 2), list))
def test_empty_make_hamburger_returns_breads(self):
self.assertEqual(make_hamburger(None, 0), ['bread', 'bread'])
def test_invalid_make_hamburger_raises(self):
with self.assertRaises(TypeError):
make_hamburger()
Unit testing?
from typing import List
def make_hamburger(meat: str, number_of_meats: int) -> List[str]:
return ["bread"] + [meat] * number_of_meats + ["bread"]
The `typing`module
from typing import List
Hamburger = List[str]
def make_hamburger(meat: str, number_of_meats: int) -> Hamburger:
return ["bread"] + [meat] * number_of_meats + ["bread"]
Type Alias
from typing import List, Optional
Hamburger = List[str]
Extras = Optional[List[str]]
def make_hamburger(meat: str, number_of_meats: int, extras: Extras) -> Hamburger:
if extras:
return ["bread"] + extras + [meat] * number_of_meats + ["bread"]
else:
return ["bread"] + [meat] * number_of_meats + ["bread"]
print(make_hamburger("Beef", 2, ['tomatoes', 'pickles']))
# ['bread', 'tomatoes', 'pickles', 'Beef', 'Beef', 'bread']
Optionals 🍅
from typing import TypeVar, List
T = TypeVar("T", int, List[str])
def generic_add(x: T, y: T) -> T:
return x + y
Generics 󰟲
x1: int = 5
y1: int = 2
print(generic_add(x1, y1)) # 7
x2: List[str] = ["Hello"]
y2: List[str] = ["World"]
print(generic_add(x2, y2)) # ['Hello', 'World']
x3: str = "foo"
y3: str = "bar"
print(generic_add(x3, y3)) # mypy error: Value of type variable "T" of
"generic_add" cannot be "str"
Generics 󰟲
from typing import Union
Number = Union[float, int]
def union_add(x: Number, y: Number) -> Number:
return x + y
Union Types
x1: int = 5
y1: float = 2.5
print(union_add(x1, y1))
# 7
x2: int = 2
y2: str = "1"
print(union_add(x2, y2))
# error: Argument 1 to "union_add" has incompatible type "str";
expected "Union[float, int]"
# error: Argument 2 to "union_add" has incompatible type "str";
expected "Union[float, int]"
Union Types
from typing import Callable
def sum_and_process(a: int, b: int, callback: Callable[[int], bool]) -> bool:
total = a + b
return callback(total)
def is_positive(val: int) -> bool:
return val > 0
output = sum_and_process(5, 2, is_positive)
print(output)
# True
Callables
How to start using types in Python with mypy
谢谢!
ευχαριστώ
Obrigado!
¡Gracias!
Thank You!
Check out my tutorial

More Related Content

PDF
Python Workshop by Tom Frantz
PPTX
Unix study class_01
TXT
Assignment6
PDF
15 6 파일 처리
PPTX
Scripting 101
PPT
Linux Basics
PDF
Go(lang) for the Rubyist
PDF
From 0 to mine sweeper in pyside
Python Workshop by Tom Frantz
Unix study class_01
Assignment6
15 6 파일 처리
Scripting 101
Linux Basics
Go(lang) for the Rubyist
From 0 to mine sweeper in pyside

Similar to How to start using types in Python with mypy (20)

PDF
Static type checking in python
PDF
Types my way: Static Typing in Python
PDF
Type hints Python 3
PDF
Python Tutorial
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
PPTX
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
PPTX
Type hints in python & mypy
DOCX
unit 1.docx
PPTX
BUILDING IoT WITH ARDUINO & RASPBERRY PI
PDF
Tip Top Typing - A Look at Python Typing
PDF
User-Defined Types.pdf
PPTX
Type Annotations in Python: Whats, Whys and Wows!
PDF
Domain Driven Design Made Functional with Python
PPTX
Data_Types_in_Python_Presentation (1).pptx
PDF
A tour of Python
PDF
An overview of Python 2.7
PPTX
Week 2 Lesson Natural Processing Language.pptx
PPTX
Robust Python.pptx
PDF
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
Static type checking in python
Types my way: Static Typing in Python
Type hints Python 3
Python Tutorial
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
Type hints in python & mypy
unit 1.docx
BUILDING IoT WITH ARDUINO & RASPBERRY PI
Tip Top Typing - A Look at Python Typing
User-Defined Types.pdf
Type Annotations in Python: Whats, Whys and Wows!
Domain Driven Design Made Functional with Python
Data_Types_in_Python_Presentation (1).pptx
A tour of Python
An overview of Python 2.7
Week 2 Lesson Natural Processing Language.pptx
Robust Python.pptx
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine

More from Carlos V. (6)

PDF
Functional Programming inside OOP? It’s possible with Python
PDF
TID Chile dataviz
PDF
Open Data in Agriculture - AGH20013 Hands-on session
PPT
APIVITA BeeNet - Athens Green Hackathon 2013
PPTX
Findjira presentación
PDF
agINFRA Workshop for LACLO2012
Functional Programming inside OOP? It’s possible with Python
TID Chile dataviz
Open Data in Agriculture - AGH20013 Hands-on session
APIVITA BeeNet - Athens Green Hackathon 2013
Findjira presentación
agINFRA Workshop for LACLO2012

Recently uploaded (20)

PDF
Decision Optimization - From Theory to Practice
PDF
The AI Revolution in Customer Service - 2025
PDF
Launch a Bumble-Style App with AI Features in 2025.pdf
PDF
NewMind AI Weekly Chronicles – August ’25 Week IV
PDF
A symptom-driven medical diagnosis support model based on machine learning te...
PDF
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
PPTX
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
PDF
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
PDF
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
PDF
Examining Bias in AI Generated News Content.pdf
PDF
substrate PowerPoint Presentation basic one
PDF
Data Virtualization in Action: Scaling APIs and Apps with FME
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PDF
Streamline Vulnerability Management From Minimal Images to SBOMs
PDF
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
PDF
IT-ITes Industry bjjbnkmkhkhknbmhkhmjhjkhj
PPTX
Report in SIP_Distance_Learning_Technology_Impact.pptx
PDF
Build Real-Time ML Apps with Python, Feast & NoSQL
PDF
giants, standing on the shoulders of - by Daniel Stenberg
Decision Optimization - From Theory to Practice
The AI Revolution in Customer Service - 2025
Launch a Bumble-Style App with AI Features in 2025.pdf
NewMind AI Weekly Chronicles – August ’25 Week IV
A symptom-driven medical diagnosis support model based on machine learning te...
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
Examining Bias in AI Generated News Content.pdf
substrate PowerPoint Presentation basic one
Data Virtualization in Action: Scaling APIs and Apps with FME
NewMind AI Journal Monthly Chronicles - August 2025
Streamline Vulnerability Management From Minimal Images to SBOMs
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
IT-ITes Industry bjjbnkmkhkhknbmhkhmjhjkhj
Report in SIP_Distance_Learning_Technology_Impact.pptx
Build Real-Time ML Apps with Python, Feast & NoSQL
giants, standing on the shoulders of - by Daniel Stenberg

How to start using types in Python with mypy

  • 1. How to start using types in Python with Mypy
  • 2. Carlos Villavicencio Ecuadorian 󰎸 Software Developer at Stack Builders Community leader Amateur photographer cvillavicencio [email protected] @po5i po5i Quilotoa Lake, Ecuador 2020. 大家好!
  • 4. Data Structures Primitive Non-primitive Integer Float String Boolean Array List Tuple Dictionary Set File Linear Non-linear Stacks Queues Graphs Trees
  • 7. Types are known in compilation time Variables bind to types Very verbose Bytecode is well optimized in memory Types are known in runtime Variables bind to objects 🦆 Less verbose Bugs in run-time are very common Dynamic vs. Static Languages
  • 8. Weakly vs. Strongly Type System Implicit coercion between non-related types Flexibles Unpredictables Explicit type conversion (casting) Strict rules on the static analysis. Type Safety
  • 9. Static type checking in Python But you can also use
  • 11. meat: str = "Beef" weight_pounds: float = "0.5" # mypy # error: Incompatible types in assignment # (expression has type "str", variable has type "float") Primitive types 🦕
  • 12. Let’s prepare some 🍔 def make_hamburger(meat, number_of_meats): return ["bread"] + [meat] * number_of_meats + ["bread"] print(make_hamburger("BEEF", 2)) # ['bread', 'BEEF', 'BEEF', 'bread']
  • 13. class MyTest(unittest.TestCase): def test_make_hamburger_returns_list(self): self.assertTrue(isinstance(make_hamburger("beef", 2), list)) def test_empty_make_hamburger_returns_breads(self): self.assertEqual(make_hamburger(None, 0), ['bread', 'bread']) def test_invalid_make_hamburger_raises(self): with self.assertRaises(TypeError): make_hamburger() Unit testing?
  • 14. from typing import List def make_hamburger(meat: str, number_of_meats: int) -> List[str]: return ["bread"] + [meat] * number_of_meats + ["bread"] The `typing`module
  • 15. from typing import List Hamburger = List[str] def make_hamburger(meat: str, number_of_meats: int) -> Hamburger: return ["bread"] + [meat] * number_of_meats + ["bread"] Type Alias
  • 16. from typing import List, Optional Hamburger = List[str] Extras = Optional[List[str]] def make_hamburger(meat: str, number_of_meats: int, extras: Extras) -> Hamburger: if extras: return ["bread"] + extras + [meat] * number_of_meats + ["bread"] else: return ["bread"] + [meat] * number_of_meats + ["bread"] print(make_hamburger("Beef", 2, ['tomatoes', 'pickles'])) # ['bread', 'tomatoes', 'pickles', 'Beef', 'Beef', 'bread'] Optionals 🍅
  • 17. from typing import TypeVar, List T = TypeVar("T", int, List[str]) def generic_add(x: T, y: T) -> T: return x + y Generics 󰟲
  • 18. x1: int = 5 y1: int = 2 print(generic_add(x1, y1)) # 7 x2: List[str] = ["Hello"] y2: List[str] = ["World"] print(generic_add(x2, y2)) # ['Hello', 'World'] x3: str = "foo" y3: str = "bar" print(generic_add(x3, y3)) # mypy error: Value of type variable "T" of "generic_add" cannot be "str" Generics 󰟲
  • 19. from typing import Union Number = Union[float, int] def union_add(x: Number, y: Number) -> Number: return x + y Union Types
  • 20. x1: int = 5 y1: float = 2.5 print(union_add(x1, y1)) # 7 x2: int = 2 y2: str = "1" print(union_add(x2, y2)) # error: Argument 1 to "union_add" has incompatible type "str"; expected "Union[float, int]" # error: Argument 2 to "union_add" has incompatible type "str"; expected "Union[float, int]" Union Types
  • 21. from typing import Callable def sum_and_process(a: int, b: int, callback: Callable[[int], bool]) -> bool: total = a + b return callback(total) def is_positive(val: int) -> bool: return val > 0 output = sum_and_process(5, 2, is_positive) print(output) # True Callables