Posts tagged ‘python’ (Page 2)

(All tags.)

Why does Python log a warning for “invalid decimal literal”?

Where did this warning come from?

Take this function:


Three Cheers for blacken-docs

Blacken all ye docs.

Black is the de facto standard code formatter for Python, and these days I use it on all my projects. blacken-docs is a tool that also allows you to apply Black to code samples in your docs. I recently rolled it out on my projects to great effect.


Python Type Hints - Use Cases for the types Module

Some kind of tool for working with types.

Writing type hints gives us some familiarity with the typing module. But Python also includes the similarly-named types module, which can also come in handy. Let’s look at the history of these two modules, some use cases of types, and one way in which it’s not so useful.


Python Type Hints - How to Work with Regular Expressions

Searching again for a needle in a haystack.

Python’s re module lets us search both str and bytes strings with regular expressions (regexes). Our type checker can ensure we call re functions with the correct types, thanks to some parametrized classes.


Python Type Hints - How to Vary Return Type Based on an Argument

So many ropes, so many overloads.

Here’s a recipe that combines typing.Literal with @overload to define a function that switches its return type based on the value of an argument.


Python Type Hints - How to Avoid “The Boolean Trap”

Well that looks like a finger trap.

“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.


Python Type Hints - How to Use typing.Literal

This scraper is apparently the kind of tool a typographer would use.

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.


Django 3.2 Update for “Speed Up Your Django Tests” Released


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 Type Hints - How to Use typing.cast()

Cast iron horseshoe

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.


Recent Updates to time-machine

This is my time machine.

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.