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

What's hot

Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
 
Multimedia on android
Multimedia on androidMultimedia on android
Multimedia on androidRamesh Prasad
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)Muhammad Hammad Waseem
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kataPaul Blundell
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoChariza Pladin
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in PythonHaim Michael
 
Python-List comprehension
Python-List comprehensionPython-List comprehension
Python-List comprehensionColin Su
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | EdurekaEdureka!
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksEueung Mulyana
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language安齊 劉
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)David Ehringer
 

What's hot (20)

Java Array String
Java Array StringJava Array String
Java Array String
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Multimedia on android
Multimedia on androidMultimedia on android
Multimedia on android
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Python basics
Python basicsPython basics
Python basics
 
Exception handling
Exception handlingException handling
Exception handling
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kata
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and Django
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
 
Python-List comprehension
Python-List comprehensionPython-List comprehension
Python-List comprehension
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | Edureka
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter Notebooks
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)
 

Similar to Type hints in python & mypy

Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
Python for katana
Python for katanaPython for katana
Python for katanakedar nath
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Andreas Dewes
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!Yusuke Miyazaki
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizeIruolagbePius
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning ParrotAI
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An IntroductionSwarit Wadhe
 
Python_Unit_1.pdf
Python_Unit_1.pdfPython_Unit_1.pdf
Python_Unit_1.pdfalaparthi
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdfShivamKS4
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to AdvancedTalentica Software
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptxYusuf Ayuba
 

Similar to Type hints in python & mypy (20)

Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Python for katana
Python for katanaPython for katana
Python for katana
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!
 
Python with data Sciences
Python with data SciencesPython with data Sciences
Python with data Sciences
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning
 
GE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_NotesGE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_Notes
 
Python Data Types
Python Data TypesPython Data Types
Python Data Types
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
intro to python.pptx
intro to python.pptxintro to python.pptx
intro to python.pptx
 
Python_Unit_1.pdf
Python_Unit_1.pdfPython_Unit_1.pdf
Python_Unit_1.pdf
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdf
 
Python Training in Chandigarh
Python Training in ChandigarhPython Training in Chandigarh
Python Training in Chandigarh
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptx
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

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