“The Boolean Trap” is a programming anti-pattern where a boolean argument switches behaviour, leading to confusion.
In this post we’ll look at the trap in more detail, and several ways to avoid it in Python, with added safety from type hints.
To put it tautologically, type hints normally specify the types of variables.
But when a variable can only contain a limited set of literal values, we can use
typing.Literal for its type.
This allows the type checker to make extra inferences, giving our code an increased level of safety.
I released my book “Speed Up Your Django Tests” over a year ago, in May 2020.
Since then, we’ve seen two major Django releases, including a whole bunch of test-related changes, some of which I worked on as part of the book.
Python’s dynamism means that, although support continues to expand, type hints will never cover every situation.
For edge cases we need to use an “escape hatch” to override the type checker.
time-machine is my library for mocking the current date and time in Python tests.
It’s now over a year old, and I just released its version 2.2.0, so I thought it would be nice to summarize recent changes.
Python’s context manager protocol has only two methods, with straightforward types.
But when it comes to adding accurate type hints to a context manager, we still need to combine several typing features.
Let’s look at how we can do this for the two different ways of making a context manager.
A “magic number” is the anti-pattern of using a number directly rather than storing it in a descriptive variable name.
In web code HTTP status codes are often used as magic numbers, perhaps because web developers memorize common codes such as 200 and 404.
In Python, we can avoid such magic with descriptive references from the standard library’s
When we add type hints, we can find our desire for strictness in tension with Python’s flexibility.
In this post we’ll explore three groups of functions in the standard library that I naïvely expected to use narrow types, but due to some edge cases, instead use
I previously covered type narrowing using
In today’s post we’ll cover
TypeGuard, a new special type that allows us to create custom type narrowing functions.
I released my book Speed Up your Django Tests (SUYDT) just over a year ago, on the 18th May.
It’s had a great reception, with 379 customers so far, many writing in to say how it has improved their test suites’ performance and readability.