Skip to Content
Hypermodern Python Tooling
book

Hypermodern Python Tooling

by Claudio Jolowicz
June 2024
Intermediate to advanced
270 pages
6h 40m
English
O'Reilly Media, Inc.
Content preview from Hypermodern Python Tooling

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

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

Python Testing with pytest

Python Testing with pytest

Brian Okken

Publisher Resources

ISBN: 9781098139575Errata PageSupplemental Content