Type-Checking Python Programs With Type Hints and mypy

Real Python · Beginner ·🛠️ AI Tools & Apps ·9y ago

Key Takeaways

The video discusses type checking in Python using type hints and mypy, a popular type checker, to catch bugs and improve code quality. It covers the basics of type hinting, type annotations, and external type checkers like mypy, as well as the benefits of type checking in Python, including fixing type checking errors and detecting big bugs in large codebases.

Full Transcript

hey everyone so this is going to be a quick intro to using the mypi type Checker to type check your Python 3 programs um if you're wondering type checking in Python um it's it's kind of a big deal right now A lot of people are talking about how this could potentially be the future of the language and just to give you a feel of of you know what type checking is actually good for so this is a new feature that was added in Python 35 and what it allows you to do is um let's say we write a simple function um let's call it at this and we just give it two arguments A and B and it's going to return a plus b right so in kind of stock python we don't really have a good idea of what the types are that this function deals with and then also what the return the type of the return value is going to be I mean you could imagine that I can call this with uh two strings and I can also call this with two integers and I could call it with a bunch more things and some of them might not even make a lot of sense so what type hinting does now is it allows me to specify the expected types for these arguments and then also for this function so I can say okay you know I expect these two arguments to be integers and then I expect this function to also return an integer and uh the way this works is that these guys here these type annotations they are um a syntax extension that was added to python 3.5 so this is not going to work in older versions of python there's a way to do that in Python 2 as well uh and it invol uh I think it works with some some comment syntax or basically putting these annotations into comments you can look that up on your own um let's for now let's focus on the Python 3 syntax and basically what these typin allow me to do is like specify the yeah like I said the expected types for these arguments and also the expected return type so right now when you look at this um it doesn't actually guarantee that this function can really handle these argument types it's just a type hint or it's just these three type hints and um you know I could just do this where I just force this function to return a string and uh it wouldn't really be an error right like matter of fact if I save this and then just run it through the um the python interpreter uh let's actually should probably call this um and call this function then the program still works even though it doesn't really follow this uh contract for for the types that we gave it now the way that types are going to be working in Python is that they're just type hints and then you need an external program almost like a linter that it's called a type Checker and you would need that type Checker program to actually look at your program code and then give you feedback on whether or not um your program code actually follows the the type annotations right so in this case uh this function would be violating its type annotations um and uh I'm going to show you now how you can actually run a type checker on this program so a really popular type Checker right now is mypie so let's install that for a second pip install my pie. Lang you want to make sure you install a pi mypie do mypie Dash Lang because just mypie without the dash Lang is something else entirely so you're not going to be happy with that cool so let's install my piie it's going to take a second here okay great and now what I'm going to do is just run my Pi on my types example.py cool and we actually got an error message here um which is great right because we we knew that our program was wasn't valid um in the sense that it was following the type annotations and so here my Pi tells us uh types example of Pi in function at this incompatible return value type got got stir expected int and this is pretty much exactly what we're saying here right and so we can fix that by changing it so it returns an INT right like we could either do something like that where we hardcode it and that would cause the type Checker to pass or we could we actually make it do something useful um like return the sum of these two and then that would still pass and you could see that you know having this uh a plus b is the return value is actually a little bit more complicated than just saying return 23 because it's kind of easy for for mypi to figure out that 23 is an integer constant but when you do actually when you actually do something like a plus b then mypi has to go and check the type off a and check the type off B and then actually figure out that if you add these two you end up with an integer as well so therefore the the typ pins um are accurate and we don't get uh a type error um so you can imagine that this technique can be scaled quite well and it actually already goes far beyond just that little experiment that I've showed you right because you know if you look at this like this wouldn't be really interesting it where it gets interesting is when you have thousands and hundreds of thousands of lines of code or millions of lines of code and you can use a tool like mypie to actually find find some um really big bugs that were previously undetected the tie hinting stuff is going to get more valuable as you have more and more code and as you you're able to kind of automatically find uh bugs that would be really hard to detect for a human in a in a ginormous code base right and kind of the make or break thing for this to work is having these typ hints already already there for let's say large parts of the Python standard library or third party libraries and so you know just to give you an example like let's say I import the random module and um I'm going to change my at this function to do something terrible which is um we're going to go and just make it return a random integer between A and B so now this still type checks cleanly which means that mypi actually understands that random Rand in returns an integer and and you know it it seems like really really straightforward for um a human because we have the the python docs and we kind of you know we're told this thing returns a random integer in range AB but um in a lot of cases like in some cases mypi might be able to infer that type and just figure it out on its own but in a lot of cases it's going to depend on people adding these type hins to functions in the um in the python standard library and also in uh other thirdparty libraries so like a big bulk of the work is is not just writing the type Checker which is you know difficult enough um it's a big project but also like a big bulk of the work is adding these type hints everywhere so that mypi and other other type checkers can be as effective as possible because if they if if a type Checker doesn't know what the the types are you're dealing with it doesn't really add a lot of value right it could still function as like a basic linter but it gets really interesting when you have all of these type checks so there's a big project right now it's I believe it's called the type shed project where people add these annotation to annotations to um the standard library to cover kind of as much of that as possible and then also people are starting to incorporate third party libraries like Jango and kind of the big popular ones and so well kind of how can I wrap this up right so because this was just meant to be as a as a small like intro video so I think I see a lot of power in in uh just having the possibility to to do CH type checking in Python because because like I said in the beginning it's going to enable a lot more use cases for python as a language which I think is awesome um and on the other hand and it's going to take a lot of work before this is really going to work seamlessly right because if you do this stuff like that in in a statically typed language like Java then um you're going to have to provide these types like from the get-go right so there never was a Java that didn't already have all of these types and that's why the compiler can work with it and can give you all this this helpful feedback but for python it's kind of the unique challenge is that the type checking stuff is going to be bolted on to Python and so now we're in this situation where you can already use this on a on a small scale like for small programs but it's going to take a little bit more time before actually all of the you know all of the other code is going to be covered well with typ hins so you can actually really use this on a larger code base without actually getting uh tons of warnings and errors that that aren't real errors that that just you know happen because the typ hints are missing or are ambiguous so all in all I think this is going to be a really interesting uh Direction python is going into and you know if you're interested in this stuff today or like now is probably a good time to get into it because then you're going to be at the Forefront of um this new language feature

Original Description

https://dbader.org/python-tricks ► Avoid the bugs that Python type hinting will catch in the first place and see how to write clean and Pythonic code Get quick intro to Python type hinting using the mypy type checker, in order to catch bugs and improve the quality of your existing Python code. In this video I'll walk you through a simple example of what Python's new type hints allow you to do, then I'll show you how to install and use the mypy type checker as a static analysis tool from the command line. At the end you'll get an outlook of the future of type checking and the type hinting syntax in Python. FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube * * * ► Python MUGS, T-SHIRTS & MORE: https://nerdlettering.com FREE Python Tutorials & News: » Python Tutorials: https://dbader.org » Python News on Twitter: https://twitter.com/@dbader_org » Weekly Tips for Pythonistas: https://dbader.org/newsletter » Subscribe to this channel: https://dbader.org/youtube
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 23 of 60

1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video teaches you how to use type hints and mypy to catch bugs and improve the quality of your Python code. You'll learn how to install mypy, run it on a Python program, and use type hints to fix type checking errors. With this knowledge, you'll be able to write cleaner and more maintainable code.

Key Takeaways
  1. Install mypy using pip
  2. Run mypy on a Python program
  3. Add type hints to your Python code
  4. Use mypy to check for type checking errors
  5. Fix type checking errors using type hints
💡 Type checking in Python with type hints and mypy can help catch bugs and improve code quality, making it a valuable tool for any Python developer.

Related AI Lessons

Up next
How to Open HPL Files (HP-GL Plotter)
File Extension Geeks
Watch →