Starting With Python's assert Statement

Real Python · Beginner ·💻 AI-Assisted Coding ·3y ago

Key Takeaways

The video demonstrates the use of Python's assert statement for debugging and testing code, including setting sanity checks, testing conditions, and checking preconditions and postconditions. It also covers best practices for using assertions, such as not using them for error handling or data validation, and disabling them in production code.

Full Transcript

using Python's assert to debug and test your code Python's assert statement allows you to write sanity checks in your code these checks are known as assertions and you can use them to test if certain assumptions remain true while you're developing your code if any of your assertions become false then you have a bug in your code assertions are a convenient tool for documenting debugging and testing code during development once you've debugged and tested your code with the help of assertions then you can turn them off to optimize the code for production assertions will help you make your code more efficient robust and reliable in this course you'll learn what assertions are and when to use them how Python's assert statement works how a cert can help you document debug and test your code have assertions can be disabled to improve performance in production and what common pitfalls you might face when using assert statements to get the most out of this course you should have previous knowledge of expressions and operators functions conditional statements and exceptions having a basic understanding of documenting debugging and testing python code is also a plus as ever real python has you covered with this course on expressions and operators this one on functions this one on conditional statements and this one on exceptions you can check out this one for documentation this one for debugging and this one for testing any code that you see running in the reple will be using the B python interpreter this is a replacement python interpreter that offers a number of enhancements including code highlighting and suggestions but any code you see running on screen will work in the python raffle which is typically accessed by typing python or Python 3 at your terminal or command line prompt so now you know what's going to be covered let's get started getting to know assertions in Python python implements a feature called assertions that are pretty useful during the development of your applications and projects you'll find this feature in several other languages too such as C and Java and it comes in handy for documenting debugging and testing your code if you're looking for a tool to strengthen your debugging and testing process then assertions are for you in this part of the course you'll learn the basics of assertions including what they are what they're good for and when you shouldn't use them in your code in Python assertions are statements that you can use to set sanity checks during the development process assertions allow you to test the correctness of your code by checking if some specific conditions remain true which can come in handy while you're debugging code the assertion condition should always be true unless you have a bug in your program if the condition turns out to be false then the assertion raises an exception and terminates the execution of the program with assertions you can set checks to make sure that invariance in your code stay invariant by doing so you can check assumptions such as preconditions and post conditions for example you can set test conditions along the lines of this argument is not none or this return value is a string these kind of checks can help you catch errors as soon as possible when you're developing a program assertions are mainly for debugging they'll help you ensure that you don't introduce new bugs while adding features and fixing other bugs in your code however they can have other interesting use cases within your development process these use cases include documenting and testing your code the primary role of assertions is to trigger the alarms when a bug appears in a program in this context assertions mean make sure that this condition remains true otherwise throw an error in practice you can use assertions to check preconditions and post conditions in your programs at development time for example programmers often place assertions at the beginning of functions to check if the input is valid preconditions and also before return values to check if the output is valid post conditions assertions make it clear that you want to check if a given condition is and remains true in Python they can also include an optional message to unambiguously describe the error or problem at hand that's why they're also an efficient tool for documenting code in this context their main advantage is their ability to take concrete action instead of being passive as comments and Doc strings are finally assertions are also ideal for writing test cases in your code you can write concise and to the point test cases because assertions provide a quick way to check if a given condition is met or not which defines whether the test passes or fails you'll learn more about these common use cases of assertions later on in the course but what about when you shouldn't use assertions in general you shouldn't use assertions for data processing or data validation because you can disable assertions in production code which ends up removing all of your assertion-based processing and validation using assertions in this way is a common Pitfall and you'll learn more about this later on in the course additionally assertions aren't an error handling tool the ultimate purpose of assertions isn't to handle errors in production but to notify you during development so you can fix them in this regard you shouldn't write code that catches assertion errors using a regular try accept statement in the next section of course you'll get started by using assert statements understanding Python's assert statements you now know what assertions are what they're good for and when you shouldn't use them in your code it's time to learn the basics of writing your own assertions first note that python implements assertions as a statement with the assert keyword rather than as a function this Behavior can be a common source of confusion and issues as you'll learn later on an assert statement consists of the assert keyword the expression or condition to test and an optional message the condition is always supposed to be true if the assertion condition is true then nothing happens and the program continues its normal execution on the other hand if the condition becomes false then assert halts the program by raising an assertion error in Python assert is a simple statement with a syntax seen on screen here expression can be any valid python expression or object which is then tested for truthiness if expression is false then the statement throws an assertion error the assertion message parameter is optional but encouraged it can hold a string describing the issue that the statement is supposed to catch here's how the statement Works in practice but the truthy expression the assertion succeeds and nothing happens in that case the program continues its normal execution in contrast a 4C expression makes the assertion fail raising an assertion error and breaking the program's execution to make your research statements clear to other developers you should add a descriptive assertion message the message in this assertion clearly states which condition should be true and what is making the condition fail note that the assertion message argument to assert is optional however it can help you better understand the condition under test and figure out the problem that you're facing so whenever you use assert it's a good idea to use a descriptive assertion message for the traceback of the assertion error exception an important Point regarding the assert syntax is the statement does not require a pair of parentheses to group the expression and the optional message in Python assert is a statement not a function using a pair of parentheses can lead to unexpected behaviors for example an assertion such as the one seen on screen will raise a syntax warning this warning has to do with non-empty tuples always being truthy in Python in this example the parentheses turn the assertion expression and message into a two item Tuple which always evaluates to true fortunately recent versions of python throw a syntax warning to alert you of this however in older versions of the language an assert statement as seen on screen will always succeed this issue often appears when you're using long expressions or messages that take more than a single line in these cases the parentheses are the natural way to format the code and you may end up with something like the code seen on screen using a pair of parentheses to split a long line into multiple lines is a common formatting practice in Python code however in the context of an assert statement the parentheses turn the assertion expression and the message into a two item two pull in practice if you want to split a long assertion into several lines then you can use the backslash character for explicit line joining the backslash at the end of the first line of this assertion joins the two physical lines into a single logical line this way you can have an appropriate line length without the risk of a warning or a logical error in your code pep 679 was created in January 2022 and is proposing to allow parentheses around the assertion expression and message if the pep gets approved and implemented then the issue of accidental tuples won't affect python code in the future there is an edge case of this parentheses related issue if you provide only the assertion expression in parentheses then assert will work just fine why is this happening to create a single item Tuple you need to place a comma after the item itself in the codon screen the parentheses by themselves don't create a tuple and that's why The Interpreter ignores the parentheses and assert works as expected even though the parentheses work in this scenario it's not a recommended practice you can end up shooting yourself in the foot if the condition of an assert statement evaluates to false then assert raises an assertion error if you provide the optional assertion message then this message is internally used as an argument to the assertion error class either way the raised exception breaks your program's execution most of the time you won't raise assertion error exceptions explicitly in your code the assert statement takes care of raising this exception when the assertion condition fails additionally as you'll learn later on you shouldn't attempt to handle Errors By writing code that catches the assertion error finally assertion error is a built-in exception that inherits from the exception class and is considered a concrete exception that should be raised instead of subclassed now you know the basics of the assert statement you've learned the statement syntax how it works in practice and also what the main characteristics of the assertion error exception are it's time to move forward and explore some effective and common ways to write assertions in Python and that's what you'll be looking at in the next section of the course exploring common assertion formats when it comes to writing the assert statement you'll find several assertion formats that are common in Python code being aware of these formats will allow you to write better assertions the examples that you'll see showcase a few of these common formats starting with assertions that compare objects comparison assertions are intended to test conditions that compare two or more objects using comparison operators these assertions can also include compound Expressions based on Boolean operators another common assertion format is related to membership tests membership assertions allow you to check if a given item is present in a specific collection such as a list Tuple set or dictionary these assertions use the membership operators in and not in to perform the required check another assertion format is related to an object's identity identity assertions provide a way to test for an object's identity in this case the assertion expression uses the identity operators is and is not finally you'll see how to check the data type of objects in the context of an assertion type check assertions commonly involve using a built-in is instance function to make sure that a given object is an instance of a certain class or classes even though these are some of the most common assertion formats that you'll find in Python code there are many other possibilities for example you can use the built-in all and any functions to write assertions that check for the truth value of items in an iterable the all assertions check if all the items in an input iterable are truthy while the any examples check if any item in the input iterable is truthy your imagination is the only limit for writing useful assertions you can write assertions using predicate or Boolean valued functions regular python objects comparison Expressions Boolean expressions or general python expressions your assertion will depend on what specific condition you need to check at any given moment now you know some of the most common assertion formats you can use in your code it's time to learn about specific use cases of assertions and in the next section of the course you'll learn how to use assertions to document your code documenting your code with assertions the assert statement is an effective way to document your code for example if you want to state that a specific condition should always be true in your code then using an assertion can be better and more effective than a comment or a doc string to understand why assertions can be a handy documenting tool let's say you have a function that takes a server name and a tuple of port numbers the function will iterate over the port numbers trying to connect to the Target server for your function to work correctly the Tuple of ports should not be empty if someone accidentally calls get response with an empty Tuple then the for Loop will never run and a function will return none even if the server is available to alert programmers to this buggy call you can use a comment as you did in the example on screen however using an assert statement can be more effective the advantage of an assert statement over a comment is that when the condition isn't true assert immediately raises an assertion error after that the code stops running so it avoids abnormal behaviors and points you directly to the specific problem using assertions in situations like this is an effective and Powerful way to document your intentions and avoid hard to find bugs due to Accidental errors or malicious actors in the next section of the course you'll increase your knowledge of assertions by looking at their use for debugging debugging your code with assertions at its core the assert statement is a debugging aid for testing conditions that should remain true during your code's normal execution for assertions to work as a debugging tool you should write them so that a failure indicates a bug in the code in this section you'll learn how to use the assert statement to assist you while debugging your code at development time you'll typically use assertions to debug your code during development the idea is to make sure that specific conditions are and remain true if an asserted condition becomes false then you immediately know you have a bug as an example check out the circle class that's seen on screen the class initializer Dunder init takes radius as an argument and makes sure that the input value is a positive number this check prevents circles with a negative radius the area method computes the circle's area however before doing that the method uses an assert statement to guarantee that radius remains a positive number why would you add this check well let's suppose you're working on a team and a co-worker needs to add the code seen on screen to Circle this method takes a correction coefficient and applies it to the current value of radius however the method doesn't validate the coefficient introducing a subtle bug Can you spot it let's say that the user provides a negative correction coefficient by accident the first call to area works correctly because the initial radius is positive but the second call to area breaks the code with an assertion error why this happens because the call to correct radius turns the radius into a negative number which uncovers a bug the function doesn't properly check for valid input in this example the assert statement works as a watchdog for situations in which the radius could take invalid values the assertion error immediately points you to the specific problem radius has unexpectedly changed to a negative number you have to figure out how this unexpected change happened and then fix your code before it goes into production developers often use assert statements to check preconditions just as you did in a previous example developers also use assertions to State Post conditions for example you can check if a function's return value is valid right before returning the value to the caller in general the conditions that you check with an assert statement should be true unless you or another developer in your team introduces a bug in the code in other words these conditions should never be false their purpose is to quickly flag if someone introduces a bug in this regard assertions are early alerts in the code which are meant to be useful during development to properly use assertions is a debugging tool you shouldn't use try accept blocks that catch and handle assertion error exceptions if an assertion fails then your program Should Crash because a condition that was supposed to be true became false you should not change this intended Behavior by catching the exception a proper use of assertions is to inform developers about unrecoverable errors in a program assertions shouldn't signal an expected error such as a phone or found error where a user can take a corrective action and try again the goal of an assertion should be to uncover programmers errors rather than users errors assertions are useful during the development process not during production by the time you release your code it should mostly be free of bugs and shouldn't require the assertions to work correctly finally once your code is ready for production you don't have to explicitly remove assertions you can just disable them and that's what you'll be looking at in the next section of the course

Original Description

Python’s assert statement allows you to write sanity checks in your code. These checks are known as assertions, and you can use them to test if certain assumptions remain true while you’re developing your code. If any of your assertions turn false, then you have a bug in your code. This is a portion of the complete course, which you can find here: https://realpython.com/courses/python-assert-statement/ The rest of the course covers how to: - How assert can help you document, debug, and test your code - How assertions can be disabled to improve performance in production - What common pitfalls you might face when using assert statements - Working with the PYTHONOPTIMIZE environment variable
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
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
23 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 Python's assert statement to write sanity checks in your code, ensuring that certain assumptions remain true during development. You'll learn how to use assertions to test conditions, check preconditions and postconditions, and improve your code quality.

Key Takeaways
  1. Use assertions to set sanity checks in code
  2. Test conditions with assertions
  3. Check preconditions and postconditions with assertions
  4. Use the assert statement to test conditions in code
  5. Compare objects using comparison operators
  6. Check if an item is present in a collection using membership operators
  7. Test for an object's identity using identity operators
  8. Use the is instance function to check the data type of an object
💡 Assertions are a powerful tool for debugging and testing code, but they should not be used for error handling or data validation, and should be disabled in production code.

Related Reads

Up next
Advanced Tutorial NotebookLM Slides For Powerpoint
Russell Stannard (TTVideos)
Watch →