Type annotations
Python is a dynamically typed language: a variable can hold a number and, later, a text. Type annotations (*type hints*) let you…
Write shorter classes and clearer programs with the modern tools of Python. In this lesson you will learn how to annotate types on variables and functions, how to create data classes with @dataclass (default values, comparison, sorting and immutability), how to define named constants with Enum and IntEnum and how to combine all of them.
Python is a dynamically typed language: a variable can hold a number and, later, a text. Type annotations (*type hints*) let you…
Many classes are only used to hold data : a point, a product, a student. Writing them by hand is repetitive:
By default, < and > do not work with dataclasses. With order=True , Python compares the objects attribute by attribute, in the…
Sometimes a variable can only take a few fixed values: the state of a task, a day of the week, a color. Using loose numbers or…
The three tools get along very well. A dataclass whose attribute is an enumeration, with type annotations, is a clear, short…
Create a Python program with a function that has type annotations and returns a dictionary with several statistics.
Create a Python program with your first dataclass : a class that generates its own constructor and its representation.
Create a Python program that compares two objects of a dataclass: @dataclass automatically generates __eq__ , which compares…
Create a Python program with a dataclass that has a list as a default value, using field(default_factory=list) .
Create a Python program with a sortable dataclass: with order=True , the objects are compared by their attributes, in the order…
Create a Python program with an immutable dataclass ( frozen=True ) and create modified versions with replace .
Create a Python program with an enumeration : a set of named constants.
Create a Python program that looks up a member of an enumeration by its name and goes through the enumeration.
Create a Python program that combines an enumeration and a dataclass to group items by category.
Create a Python program with an IntEnum : an enumeration whose members are integers and can therefore be compared with >= .