SlideShare a Scribd company logo
Types my way: Static typing in Python
Joe Cabrera
Dynamically typing
The Python interpreter checks types as your code runs and the type of variable
can change during it’s lifetime
>>> thing = "hello"
>>> type(thing)
<class 'str'>
>>> thing = 29.0
>>> type(thing)
<class 'float'>
Static Typing
Static typing checks run without even running the program, usually when the code
is compiled (C++ and Java)
String thing;
thing = "Hello";
Duck Typing
“If it walks like a duck and it quacks like a duck, this it must be a duck”
You do not check types at all, instead you check if an object has a method or
attribute
>>> class Malort:
... def __str__(self):
... return "Jeppson's Malört"
... def __format__(self, format):
... if(format == 'where'):
... return "only in chicago"
... return "None"
...
>>> print(format(Malort(), "where"))
only in chicago
def get_caching_header(args=None):
"""
Get cache header dictionary.
:param args: Query arguments for used to build surrogate key
:type args: dict
:return: Cache header dictionary
"""
def get_caching_header(args=None):
"""
Get cache header dictionary.
"""
assert type(args) is dict
Optional Type Checking
- Compile-time type checking
- Easier to find bugs
- Less debugging
- Easier maintenance
- Machine-checked documentation
- Easier to understand code
- Grow from dynamic to static typing
- You can add static typing existing codebases after your code has matured
- You can gradually add type hints with Any
Why should you start type checking now?
● Great for complex and confusing code
● Good for open-source code
● Before migrating or refactoring code
PEP 484: Type Hints
Python will remain a dynamically typed language, and the authors have no desire
to ever make type hints mandatory, even by convention.
Type hints have no runtime effect
>>> def shot(location: str) -> str:
... if location == "new york":
... return "hennessy"
... elif location == "chicago":
... return "evan williams"
... else:
... return "jack daniels"
Function annotations
Functions can have annotation arguments and return value
>>> def beer(location: str, with_shot: bool = True) -> str:
...
>>> beer.__annotations__
{'location': <class 'str'>, 'with_shot': <class 'bool'>}
Variable annotations
Available since Python 3.6
>>> speed_of_sound: float = 343.0
Type & Variable Comments
Annotations are great, but have not been backported to Python 2.x
Type comments can be used in any version of Python
>>> def beer(location, with_shot):
>>> # type: (str, bool) -> str
>>> ...
>>> speed_of_sound = 343.0 # type: float
Sequences & Mappings
Great we can do primitives but what about composite types. Also not an issue…
>>> beers: list = ["Coors Light", "Budweiser", "Corona"]
>>> shots: tuple = ("B-52", "Irish Car Bomb", "Lemon Drop")
>>> beer_shot: dict = {"Coors Light": "Jack Daniels", "Corona": "Tequila"}
Typing module
Composite types are great, but what about the individual values
>>> from typing import Dict, List, Tuple
>>> beers: List[str] = ["Coors Light", "Budweiser", "Corona"]
>>> shots: Tuple[str, str, str] = ("B-52", "Irish Car Bomb", "Lemon
Drop")
>>> beer_shot: Dict[str, str] = {"Coors Light": "Jack Daniels",
>>> ... "Corona": "Tequila"}
Sequences
Many times you expect some kind of sequence but do not care if it’s a list or a
tuple
>>> from typing import List, Sequence
>>>
>>> def take_shot(liquors: Sequence[str]) -> str:
>>> return random.choice(liquors)
Type Aliases
Instead of
Write this
>>> from typing import List, Tuple
>>>
>>> def take_shots(beer_shot: List[Tuple[str, str]]) -> Tuple[
>>> List[Tuple[str, str]],
>>> List[Tuple[str, str]],
>>> List[Tuple[str, str]],
>>> ]:
>>> return (beer_shot[0::3], beer_shot[1::3], beer_shot[2::3])
>>> from typing import List, Tuple
>>> Boilermaker = Tuple[str, str]
Functions without return values
>>> def shot(location: str) -> None:
... if location == "new york":
... print("hennessy")
... elif location == "chicago":
... print("evan williams")
... else:
... print("jack daniels")
>>> from typing import NoReturn
>>>
>>> def the_darkness() -> NoReturn:
raise Exception("It's too late")
The magically Any type
>>> from typing import Any, Sequence
>>>
>>> def take_shot(liquors: Sequence[Any]) -> Any:
>>> return random.choice(liquors)
The Optional Type
For functions that have a default value for an argument
>>> from typing import Sequence, Optional
>>>
>>> def beer_order(names: Sequence[str],
>>> ... start: Optional[str] = None) -> Sequence[str]:
The Union Type
When you need arguments of several types in a composite
>>> from typing import Union
>>>
>>> def beer_order(nashville_beer: Union[str, int]) -> Sequence[str]:
Annonating *args and **kwargs
>>> class Bar
>>> def __init__(self, beers: List[Beer],
>>> *customer: str,
>>> **drink_types: str) -> None:
>>> self.beers = beers
Callables
>>> from typing import Callable
>>>
>>> def take_shot(func: Callable[[str], str], argument: str) -> None:
>>> print(func(argument))
>>>
>>> def create_response(liquor: str) -> str:
>>> return f"A shot of {liquor}"
>>>
>>> take_shot(create_response, "Jack Daniels")
Protocols
>>> class Bar:
>>> def meth(self) -> int:
>>> return 0
>>>
>>> def func(x: Proto) -> int:
>>> return x.meth()
Classes as Types
>>> class Bar
>>> def __init__(self, beers: List[Beer]) -> None:
>>> self.beers = beers
>>>
>>> @classmethod
>>> def open(cls, restock: bool = False) -> "Bar":
return cls(beers)
Coming in Python 4.0
>>> from __future__ import annotations
>>>
>>> class Bar
>>>
>>> @classmethod
>>> def open(cls, restock: bool = False) -> Bar:
>>> return cls(beers)
Type-checkers
Static
● MyPy (Dropbox)
● PyType (Google)
● Pyre (Facebook)
● Pyright (Microsoft)
● PyCharm
Dynamic
● Enforce, Typeguard, Typo
Thanks!
@greedoshotlast
Ad

Recommended

Интерфейсы в Python
Интерфейсы в Python
Andrew Svetlov
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ application
Daniele Pallastrelli
 
A swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
Beware: Sharp Tools
Beware: Sharp Tools
chrismdp
 
Beware sharp tools
Beware sharp tools
AgileOnTheBeach
 
... now write an interpreter (PHPem 2016)
... now write an interpreter (PHPem 2016)
James Titcumb
 
Haxe: What Makes It Cool
Haxe: What Makes It Cool
eddieSullivan
 
Pratt Parser in Python
Pratt Parser in Python
Percolate
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
Jason Yeo Jie Shun
 
Developing iOS apps with Swift
Developing iOS apps with Swift
New Generation Applications
 
Concurrent Application Development using Scala
Concurrent Application Development using Scala
Siarhiej Siemianchuk
 
Unit test
Unit test
David Xie
 
Dependent Types with Idris
Dependent Types with Idris
Abdulsattar Mohammed
 
Javascript Common Mistakes
Javascript Common Mistakes
동수 장
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
Groovy grails types, operators, objects
Groovy grails types, operators, objects
Husain Dalal
 
6 new ES6 features
6 new ES6 features
Kyle Dorman
 
Selfish presentation - ruby internals
Selfish presentation - ruby internals
Wojciech Widenka
 
Namespaces
Namespaces
zindadili
 
ES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Whats New In C# 3.0
Whats New In C# 3.0
Clint Edmonson
 
Testing For Unicorns
Testing For Unicorns
Alex Soto
 
PyLecture1 -Python Basics-
PyLecture1 -Python Basics-
Yoshiki Satotani
 
Cifrado cesar
Cifrado cesar
EIYSC
 
EcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
Scroll pHAT HD に美咲フォント
Scroll pHAT HD に美咲フォント
Yuriko IKEDA
 
Assignment
Assignment
Ayesha Bhatti
 
Exploring ES6
Exploring ES6
Ximing Dai
 
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
 

More Related Content

What's hot (20)

Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
Jason Yeo Jie Shun
 
Developing iOS apps with Swift
Developing iOS apps with Swift
New Generation Applications
 
Concurrent Application Development using Scala
Concurrent Application Development using Scala
Siarhiej Siemianchuk
 
Unit test
Unit test
David Xie
 
Dependent Types with Idris
Dependent Types with Idris
Abdulsattar Mohammed
 
Javascript Common Mistakes
Javascript Common Mistakes
동수 장
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
Groovy grails types, operators, objects
Groovy grails types, operators, objects
Husain Dalal
 
6 new ES6 features
6 new ES6 features
Kyle Dorman
 
Selfish presentation - ruby internals
Selfish presentation - ruby internals
Wojciech Widenka
 
Namespaces
Namespaces
zindadili
 
ES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Whats New In C# 3.0
Whats New In C# 3.0
Clint Edmonson
 
Testing For Unicorns
Testing For Unicorns
Alex Soto
 
PyLecture1 -Python Basics-
PyLecture1 -Python Basics-
Yoshiki Satotani
 
Cifrado cesar
Cifrado cesar
EIYSC
 
EcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
Scroll pHAT HD に美咲フォント
Scroll pHAT HD に美咲フォント
Yuriko IKEDA
 
Assignment
Assignment
Ayesha Bhatti
 
Exploring ES6
Exploring ES6
Ximing Dai
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
Jason Yeo Jie Shun
 
Concurrent Application Development using Scala
Concurrent Application Development using Scala
Siarhiej Siemianchuk
 
Javascript Common Mistakes
Javascript Common Mistakes
동수 장
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
Groovy grails types, operators, objects
Groovy grails types, operators, objects
Husain Dalal
 
6 new ES6 features
6 new ES6 features
Kyle Dorman
 
Selfish presentation - ruby internals
Selfish presentation - ruby internals
Wojciech Widenka
 
ES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Testing For Unicorns
Testing For Unicorns
Alex Soto
 
PyLecture1 -Python Basics-
PyLecture1 -Python Basics-
Yoshiki Satotani
 
Cifrado cesar
Cifrado cesar
EIYSC
 
EcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
Scroll pHAT HD に美咲フォント
Scroll pHAT HD に美咲フォント
Yuriko IKEDA
 

Similar to Types my way: Static Typing in Python (20)

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
 
Static type checking in python
Static type checking in python
Sebastian Wagner
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
Andreas Dewes
 
Type hints in python & mypy
Type hints in python & mypy
Anirudh
 
Porting to Python 3
Porting to Python 3
Lennart Regebro
 
型ヒントについて考えよう!
型ヒントについて考えよう!
Yusuke Miyazaki
 
How to start using types in Python with mypy
How to start using types in Python with mypy
Carlos V.
 
Enjoy Type Hints and its benefits
Enjoy Type Hints and its benefits
masahitojp
 
unit 1.docx
unit 1.docx
ssuser2e84e4
 
The Benefits of Type Hints
The Benefits of Type Hints
masahitojp
 
Python Tutorial
Python Tutorial
Eueung Mulyana
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
upendramaurya11
 
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
manikbuma
 
Quick python reference
Quick python reference
Jayant Parida
 
PYTHON OBJECTS - Copy.pptx
PYTHON OBJECTS - Copy.pptx
sanchiganandhini
 
Type hints Python 3
Type hints Python 3
Piotr Pałkiewicz
 
Datatypes in Python.pdf
Datatypes in Python.pdf
king931283
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
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
 
Static type checking in python
Static type checking in python
Sebastian Wagner
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
Andreas Dewes
 
Type hints in python & mypy
Type hints in python & mypy
Anirudh
 
型ヒントについて考えよう!
型ヒントについて考えよう!
Yusuke Miyazaki
 
How to start using types in Python with mypy
How to start using types in Python with mypy
Carlos V.
 
Enjoy Type Hints and its benefits
Enjoy Type Hints and its benefits
masahitojp
 
The Benefits of Type Hints
The Benefits of Type Hints
masahitojp
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
upendramaurya11
 
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
manikbuma
 
Quick python reference
Quick python reference
Jayant Parida
 
PYTHON OBJECTS - Copy.pptx
PYTHON OBJECTS - Copy.pptx
sanchiganandhini
 
Datatypes in Python.pdf
Datatypes in Python.pdf
king931283
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Ad

Recently uploaded (20)

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
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
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
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
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
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
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
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
Ad

Types my way: Static Typing in Python

  • 1. Types my way: Static typing in Python Joe Cabrera
  • 2. Dynamically typing The Python interpreter checks types as your code runs and the type of variable can change during it’s lifetime >>> thing = "hello" >>> type(thing) <class 'str'> >>> thing = 29.0 >>> type(thing) <class 'float'>
  • 3. Static Typing Static typing checks run without even running the program, usually when the code is compiled (C++ and Java) String thing; thing = "Hello";
  • 4. Duck Typing “If it walks like a duck and it quacks like a duck, this it must be a duck” You do not check types at all, instead you check if an object has a method or attribute >>> class Malort: ... def __str__(self): ... return "Jeppson's Malört" ... def __format__(self, format): ... if(format == 'where'): ... return "only in chicago" ... return "None" ... >>> print(format(Malort(), "where")) only in chicago
  • 5. def get_caching_header(args=None): """ Get cache header dictionary. :param args: Query arguments for used to build surrogate key :type args: dict :return: Cache header dictionary """
  • 6. def get_caching_header(args=None): """ Get cache header dictionary. """ assert type(args) is dict
  • 7. Optional Type Checking - Compile-time type checking - Easier to find bugs - Less debugging - Easier maintenance - Machine-checked documentation - Easier to understand code - Grow from dynamic to static typing - You can add static typing existing codebases after your code has matured - You can gradually add type hints with Any
  • 8. Why should you start type checking now? ● Great for complex and confusing code ● Good for open-source code ● Before migrating or refactoring code
  • 9. PEP 484: Type Hints Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention. Type hints have no runtime effect >>> def shot(location: str) -> str: ... if location == "new york": ... return "hennessy" ... elif location == "chicago": ... return "evan williams" ... else: ... return "jack daniels"
  • 10. Function annotations Functions can have annotation arguments and return value >>> def beer(location: str, with_shot: bool = True) -> str: ... >>> beer.__annotations__ {'location': <class 'str'>, 'with_shot': <class 'bool'>}
  • 11. Variable annotations Available since Python 3.6 >>> speed_of_sound: float = 343.0
  • 12. Type & Variable Comments Annotations are great, but have not been backported to Python 2.x Type comments can be used in any version of Python >>> def beer(location, with_shot): >>> # type: (str, bool) -> str >>> ... >>> speed_of_sound = 343.0 # type: float
  • 13. Sequences & Mappings Great we can do primitives but what about composite types. Also not an issue… >>> beers: list = ["Coors Light", "Budweiser", "Corona"] >>> shots: tuple = ("B-52", "Irish Car Bomb", "Lemon Drop") >>> beer_shot: dict = {"Coors Light": "Jack Daniels", "Corona": "Tequila"}
  • 14. Typing module Composite types are great, but what about the individual values >>> from typing import Dict, List, Tuple >>> beers: List[str] = ["Coors Light", "Budweiser", "Corona"] >>> shots: Tuple[str, str, str] = ("B-52", "Irish Car Bomb", "Lemon Drop") >>> beer_shot: Dict[str, str] = {"Coors Light": "Jack Daniels", >>> ... "Corona": "Tequila"}
  • 15. Sequences Many times you expect some kind of sequence but do not care if it’s a list or a tuple >>> from typing import List, Sequence >>> >>> def take_shot(liquors: Sequence[str]) -> str: >>> return random.choice(liquors)
  • 16. Type Aliases Instead of Write this >>> from typing import List, Tuple >>> >>> def take_shots(beer_shot: List[Tuple[str, str]]) -> Tuple[ >>> List[Tuple[str, str]], >>> List[Tuple[str, str]], >>> List[Tuple[str, str]], >>> ]: >>> return (beer_shot[0::3], beer_shot[1::3], beer_shot[2::3]) >>> from typing import List, Tuple >>> Boilermaker = Tuple[str, str]
  • 17. Functions without return values >>> def shot(location: str) -> None: ... if location == "new york": ... print("hennessy") ... elif location == "chicago": ... print("evan williams") ... else: ... print("jack daniels") >>> from typing import NoReturn >>> >>> def the_darkness() -> NoReturn: raise Exception("It's too late")
  • 18. The magically Any type >>> from typing import Any, Sequence >>> >>> def take_shot(liquors: Sequence[Any]) -> Any: >>> return random.choice(liquors)
  • 19. The Optional Type For functions that have a default value for an argument >>> from typing import Sequence, Optional >>> >>> def beer_order(names: Sequence[str], >>> ... start: Optional[str] = None) -> Sequence[str]:
  • 20. The Union Type When you need arguments of several types in a composite >>> from typing import Union >>> >>> def beer_order(nashville_beer: Union[str, int]) -> Sequence[str]:
  • 21. Annonating *args and **kwargs >>> class Bar >>> def __init__(self, beers: List[Beer], >>> *customer: str, >>> **drink_types: str) -> None: >>> self.beers = beers
  • 22. Callables >>> from typing import Callable >>> >>> def take_shot(func: Callable[[str], str], argument: str) -> None: >>> print(func(argument)) >>> >>> def create_response(liquor: str) -> str: >>> return f"A shot of {liquor}" >>> >>> take_shot(create_response, "Jack Daniels")
  • 23. Protocols >>> class Bar: >>> def meth(self) -> int: >>> return 0 >>> >>> def func(x: Proto) -> int: >>> return x.meth()
  • 24. Classes as Types >>> class Bar >>> def __init__(self, beers: List[Beer]) -> None: >>> self.beers = beers >>> >>> @classmethod >>> def open(cls, restock: bool = False) -> "Bar": return cls(beers)
  • 25. Coming in Python 4.0 >>> from __future__ import annotations >>> >>> class Bar >>> >>> @classmethod >>> def open(cls, restock: bool = False) -> Bar: >>> return cls(beers)
  • 26. Type-checkers Static ● MyPy (Dropbox) ● PyType (Google) ● Pyre (Facebook) ● Pyright (Microsoft) ● PyCharm Dynamic ● Enforce, Typeguard, Typo