Skip to Content
Robust Python
book

Robust Python

by Patrick Viafore
July 2021
Intermediate to advanced
378 pages
9h 35m
English
O'Reilly Media, Inc.
Book available
Content preview from Robust Python

Chapter 4. Constraining Types

Many developers learn the basic type annotations and call it a day. But we’re far from done. There is a wealth of advanced type annotations that are invaluable. These advanced type annotations allow you to constrain types, further restricting what they can represent. Your goal is to make illegal states unrepresentable. Developers should physically not be able to create types that are contradictory or otherwise invalid in your system. You can’t have errors in your code if it’s impossible to create the error in the first place. You can use type annotations to achieve this very goal, saving time and money. In this chapter I’ll teach you six different techniques:

Optional

Use to replace None references in your codebase.

Union

Use to present a selection of types.

Literal

Use to restrict developers to very specific values.

Annotated

Use to provide additional description of your types.

NewType

Use to restrict a type to a specific context.

Final

Use to prevent variables from being rebound to a new value.

Let’s start with handling None references with Optional types.

Optional Type

Null references are often referred to as the “billion-dollar mistake,” coined by C.A.R. Hoare:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language. My goal was to ensure that all use of references should be absolutely ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Dead Simple Python

Dead Simple Python

Jason C. McDonald
Fluent Python

Fluent Python

Luciano Ramalho

Publisher Resources

ISBN: 9781098100650Errata PageSupplemental Content