Chapter 10. Using Types for Safety and Inspection

What’s a type? As a first approximation, let’s say the type of a variable specifies the kind of values you can assign to it—​for example, integers or lists of strings. When Guido van Rossum created Python, most popular programming languages fell into two camps when it came to types: static and dynamic typing.

Statically typed languages, like C++, require you to declare the types of variables upfront (unless the compiler is smart enough to infer them automatically). In exchange, compilers ensure a variable only ever holds compatible values. That eliminates entire classes of bugs. It also enables optimizations: compilers know how much space the variable needs to store its values.

Dynamically typed languages break with this paradigm: they let you assign any value to any variable. Scripting languages like JavaScript and Perl even convert values implicitly—​say, from strings to numbers. This radically speeds up the process of writing code. It also gives you more leeway to shoot yourself into the foot.

Python is a dynamically typed language, yet it chose a middle ground between the opposing camps. Let’s demonstrate its approach with an example:

import math

number = input("Enter a number: ")
number = float(number)
result = math.sqrt(number)

print(f"The square root of {number} is {result}.")

In Python, a variable is just a name for a value. Variables don’t have types—values do. The program associates the same name, number, first with a ...

Get Hypermodern Python Tooling now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.