Pycon Israel 2021

When is an exception not an exception? Using warnings in Python
05-03, 10:00–10:25 (Asia/Jerusalem), General Track 1

Python's warnings are exceptions — but they're also distinct from exceptions, and are both used and trapped differently. In this talk, I'll introduce warnings, how to raise, trap, and redirect them, and show you best practices for their use.


If your code encounters a big problem, then you probably want to raise an exception. But what should your code do if it finds a small problem, one that shouldn't be ignored, but that doesn't merit an exception? Python's answer to this question is warnings.

In this talk, I'll introduce Python's warnings, close cousins to exceptions but still distinct from them. We'll see how you can generate warnings, and what happens when you do. But then we'll dig deeper, looking at how you can filter and redirect warnings, telling Python which types of warnings you want to see, and which you want to hide. We'll also see how you can get truly fancy, turning some warnings into (potentially fatal) exceptions and handling certain types with custom callback functions.

After this talk, you'll be able to take advantage of Python's warning system, letting your users know when something is wrong without having to choose between "print" and a full-blown exception.


Session language

English

Target audience

Developers, Testers/QA, Integrators

Reuven Lerner is a full-time Python trainer. In a given year, he teaches courses at companies in the United States, Europe, Israel, India, and China — as well as to people around the world, via his online courses, including Weekly Python Exercise.

Reuven’s most recent book is “Python Workout,” a collection of Python exercises with extensive explanations, published by Manning. He is currently working on "Pandas Workout," a similar collection of exercises for Pandas.

Reuven’s free, weekly Better developers newsletter, about Python and software engineering, is read by more than 20,000 developers around the globe. His “Trainer weekly” newsletter is similarly popular among people who give corporate training.

Reuven has a bachelor’s degree in computer science and engineering from MIT, and a PhD in learning sciences from Northwestern University. He lives in Modi’in, Israel with his wife and three children.

This speaker also appears in: