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

Recommended

Probabilistic retrieval model
Probabilistic retrieval model
baradhimarch81
 
6th commandment
6th commandment
Slater Morilla
 
Digital library technologies
Digital library technologies
Shriram Pandey
 
Basics of Information Sources in Reference Services
Basics of Information Sources in Reference Services
Allana Delgado
 
Images of pastoral care
Images of pastoral care
Rev. Stacy Burdick
 
Static type checking in python
Static type checking in python
Sebastian Wagner
 
Types my way: Static Typing in Python
Types my way: Static Typing in Python
Joe Cabrera
 
Type hints Python 3
Type hints Python 3
Piotr Pałkiewicz
 
Python Tutorial
Python Tutorial
Eueung Mulyana
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
ssuser0b643d
 
Type hints in python & mypy
Type hints in python & mypy
Anirudh
 
unit 1.docx
unit 1.docx
ssuser2e84e4
 
BUILDING IoT WITH ARDUINO & RASPBERRY PI
BUILDING IoT WITH ARDUINO & RASPBERRY PI
manohar011101110
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
Patrick Viafore
 
User-Defined Types.pdf
User-Defined Types.pdf
Patrick Viafore
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
Andreas Dewes
 
Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python
Jean Carlo Machado
 
Data_Types_in_Python_Presentation (1).pptx
Data_Types_in_Python_Presentation (1).pptx
KousarNadaf2
 
A tour of Python
A tour of Python
Aleksandar Veselinovic
 
An overview of Python 2.7
An overview of Python 2.7
decoupled
 
Week 2 Lesson Natural Processing Language.pptx
Week 2 Lesson Natural Processing Language.pptx
balmedinajewelanne
 
Robust Python.pptx
Robust Python.pptx
Patrick Viafore
 
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
Frankie Dintino
 
What's new in Python 3.11
What's new in Python 3.11
Henry Schreiner
 
Data types in python lecture (2)
Data types in python lecture (2)
Ali ٍSattar
 
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
NikhilKumar528311
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
Carlos V.
 
TID Chile dataviz
TID Chile dataviz
Carlos V.
 

More Related Content

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

Python Tutorial
Python Tutorial
Eueung Mulyana
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
ssuser0b643d
 
Type hints in python & mypy
Type hints in python & mypy
Anirudh
 
unit 1.docx
unit 1.docx
ssuser2e84e4
 
BUILDING IoT WITH ARDUINO & RASPBERRY PI
BUILDING IoT WITH ARDUINO & RASPBERRY PI
manohar011101110
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
Patrick Viafore
 
User-Defined Types.pdf
User-Defined Types.pdf
Patrick Viafore
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
Andreas Dewes
 
Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python
Jean Carlo Machado
 
Data_Types_in_Python_Presentation (1).pptx
Data_Types_in_Python_Presentation (1).pptx
KousarNadaf2
 
A tour of Python
A tour of Python
Aleksandar Veselinovic
 
An overview of Python 2.7
An overview of Python 2.7
decoupled
 
Week 2 Lesson Natural Processing Language.pptx
Week 2 Lesson Natural Processing Language.pptx
balmedinajewelanne
 
Robust Python.pptx
Robust Python.pptx
Patrick Viafore
 
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
Frankie Dintino
 
What's new in Python 3.11
What's new in Python 3.11
Henry Schreiner
 
Data types in python lecture (2)
Data types in python lecture (2)
Ali ٍSattar
 
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
NikhilKumar528311
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
ssuser0b643d
 
Type hints in python & mypy
Type hints in python & mypy
Anirudh
 
BUILDING IoT WITH ARDUINO & RASPBERRY PI
BUILDING IoT WITH ARDUINO & RASPBERRY PI
manohar011101110
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
Patrick Viafore
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
Andreas Dewes
 
Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python
Jean Carlo Machado
 
Data_Types_in_Python_Presentation (1).pptx
Data_Types_in_Python_Presentation (1).pptx
KousarNadaf2
 
An overview of Python 2.7
An overview of Python 2.7
decoupled
 
Week 2 Lesson Natural Processing Language.pptx
Week 2 Lesson Natural Processing Language.pptx
balmedinajewelanne
 
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
Frankie Dintino
 
What's new in Python 3.11
What's new in Python 3.11
Henry Schreiner
 
Data types in python lecture (2)
Data types in python lecture (2)
Ali ٍSattar
 
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
Modulebajajajjajaaja shejjsjs sisiisi 4.pptx
NikhilKumar528311
 

More from Carlos V. (6)

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

Recently uploaded (20)

Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Ad

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