Python is great for writing scripts for the command line. In this post we’ll look at my script template, an example script, and some alternative versions (without type hints, and in async flavour).
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’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.
“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.
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.
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.
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 Any.