Using String, Math and Type-Annotating Constants
00:00 String, Math, and Type-Annotating Constants You’ll find many useful constants in the standard library. Some of them are tightly connected to some specific modules, functions, and classes.
00:12 Others are more generic and you can use them in various scenarios. That’s the case with some math and string-related constants that you can find in the math and string modules respectively.
00:23
You can see the constants the math
module provides on screen. These will come in handy whenever you’re writing math-related code or even code that just uses them to perform specific computations, such as the Circle
class you created earlier on.
00:40
On screen is an updated implementation of Circle
using Math.PI
instead of the custom PI constant.
00:51
The updated version of Circle
is more readable than the original version because it provides more context on where the PI constant comes from making it clear that it’s a math-related constant.
01:01
The Math.PI
constant also has the advantage that if you’re using an old version of Python, you’ll get a 32-bit version of pi. In contrast, if you use Circle
in a modern version of Python, you’ll get a 64-bit version of pi, so the program will self adapt to the concrete execution environment.
01:20 The string module defines several useful string constants. You can see them on screen. These string related constants come in handy in many situations. You can use them when you’re doing a lot of string processing, working with regular expressions, processing natural language, and more.
01:39
Since Python 3.8, the Typing
module includes a Final
class that allows you to type annotate constants. If you use this class, when defining your constants, you’ll tell static type checkers, such as mypy, that your constants shouldn’t be reassigned.
01:54
This way the type checker can help you detect unauthorized assignments on your constants. On screen are some examples of using Final
to define constants.
02:09
The Final
class represents a special typing construct that indicates to type checkers that they should report an error if the name at hand is reassigned at some point later in the code.
02:21
A toy example of this is shown in the code, which prints the value of MAX_SPEED
, reassigns it, and then prints it again.
02:36 Running the code does what you’d expect. The code runs without issue and the value has been reassigned. But when you run a type checker such as mypy, it reports that the value should not be changed.
02:50
So Final
doesn’t prevent accidental constant reassignments at runtime, but it can help to allow type checkers to analyze code and highlight issues such as these.
02:59 In the next section of the course, you’ll take a look at some methods that will allow you to define strict constants in Python.
Become a Member to join the conversation.