Skip to content

Commit

Permalink
Add materials for full Python 3.12 tutorial (#440)
Browse files Browse the repository at this point in the history
* Add files from the full Python 3.12 tutorial

* Update README with information about new files

* Use correct numbers for sales.py and add a quick histogram

* Final QA updates
  • Loading branch information
gahjelle authored Sep 29, 2023
1 parent e06ae43 commit ec3309e
Show file tree
Hide file tree
Showing 12 changed files with 213 additions and 1 deletion.
18 changes: 17 additions & 1 deletion python-312/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Note that for the `perf` support, you'll need to build Python from source code w

You can learn more about Python 3.12's new features in the following Real Python tutorials:

- [Python 3.12: Cool New Features for You to Try](https://realpython.com/python312-new-features/)
- [Python 3.12 Preview: Ever Better Error Messages](https://realpython.com/python312-error-messages/)
- [Python 3.12 Preview: Support For the Linux `perf` Profiler](https://realpython.com/python312-perf-profiler/)
- [Python 3.12 Preview: More Intuitive and Consistent F-Strings](https://realpython.com/python312-f-strings/)
Expand All @@ -38,7 +39,7 @@ You can swap the import statement to `import d from this` in either of the files
SyntaxError: Did you mean to use 'from ... import ...' instead?
```

In [`local_self.py`](error-messages/local_self.py), you can see a naive reproduction of another improved error message. Pick apart the example code to learn more about how this was implemented in Python 3.12.
In [`local_self.py`](error-messages/local_self.py), you can see a naive reproduction of another improved error message. Pick apart the example code to learn more about how this was implemented in Python 3.12. You can also run [`shapes.py`](error-messages/shapes.py) to see the _self_ error message in action.

See [Ever Better Error Messages in Python 3.12](https://realpython.com/python312-error-messages/) for more information.

Expand Down Expand Up @@ -153,6 +154,7 @@ You can then run type checks by running `pyright`. For some features, you need t
You can find comparisons between the old and the new syntax for type variables in the following files, with the new 3.12 syntax shown in the commented part of the code:

- [`generic_queue.py`](typing/generic_queue.py)
- [`generic_stack.py`](typing/generic_stack.py)
- [`list_helpers.py`](typing/list_helpers.py)
- [`concatenation.py`](typing/concatenation.py)
- [`inspect_string.py`](typing/inspect_string.py)
Expand All @@ -165,10 +167,24 @@ Additionally, [`typed_queue.py`](typing/typed_queue.py) shows the implementation

The file [`quiz.py`](typing/quiz.py) shows how to use the new `@override` decorator. In addition to the code in the tutorial, this file includes support for reading questions from files. This is done to show that `@override` works well together with other decorators like `@classmethod`.

Similarly, [`accounts.py`](typing/accounts.py) contains the bank account classes annotated with `@override`. To play with the bank account code, you should run it interactively: `python -i accounts.py`.

#### Annotating `**kwargs` With Typed Dictionaries

The file [`options.py`](typing/options.py) shows how you can use a typed dictionary to annotate variable keyword arguments.

### Inlined Comprehensions

You can run benchmarks on comprehensions by running [`comprehension_benchmark.py`](comprehension_benchmark.py). If you have multiple versions of Python, then you should run the benchmarks on all of them and compare the results.

### Group Iterables Into Batches With `itertools.batched()`

Run [`quarters.py`](quarters.py) for an example showing how to group months into quarters.

### List Files and Directories With `Path.walk()`

Run [`pathlib_walk.py`](pathlib_walk.py) to compare `.walk()` and `.rglob()` for listing files and directories.

## Authors

- **Martin Breuss**, E-mail: [[email protected]]([email protected])
Expand Down
65 changes: 65 additions & 0 deletions python-312/comprehension_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import sys
import timeit
from functools import partial

NUM_REPEATS = 100


def convert_unit(value):
for unit in ["s", "ms", "μs", "ns"]:
if value > 1:
return f"{value:8.2f}{unit}"
value *= 1000


def timer(func):
def _timer(*args, **kwargs):
tictoc = timeit.timeit(
partial(func, *args, **kwargs), number=NUM_REPEATS
)
print(f"{func.__name__:<20} {convert_unit((tictoc) / NUM_REPEATS)}")

return _timer


@timer
def plain(numbers):
return [number for number in numbers]


@timer
def square(numbers):
return [number**2 for number in numbers]


@timer
def filtered(numbers):
return [number for number in numbers if number % 2 == 0]


n, N = 100, 100_000
small_numbers = range(n)
big_numbers = range(N)
repeated_numbers = [1 for _ in range(N)]

print(sys.version)

print("\nOne item iterable:")
plain([0])
square([0])
filtered([0])

print(f"\nSmall iterable ({n = :,}):")
plain(small_numbers)
square(small_numbers)
filtered(small_numbers)

print(f"\nBig iterable ({N = :,}):")
plain(big_numbers)
square(big_numbers)
filtered(big_numbers)

print(f"\nRepeated iterable ({N = :,}):")
plain(repeated_numbers)
square(repeated_numbers)
filtered(repeated_numbers)
13 changes: 13 additions & 0 deletions python-312/error-messages/shapes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from math import pi


class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return pi * radius**2 # noqa: F821


if __name__ == "__main__":
Circle(5).area()
20 changes: 20 additions & 0 deletions python-312/pathlib_walk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from pathlib import Path

data_path = Path(__file__).parent / "pathlib_walk"


def headline(text):
print(f"\n{text}\n{'-' * len(text)}")


headline("Using .rglob():")
for path in data_path.rglob("*"):
print(path)

headline("Using .walk():")
for path, directories, files in data_path.walk():
print(path, directories, files)

headline("Using .walk(top_down=False):")
for path, directories, files in data_path.walk(top_down=False):
print(path, directories, files)
1 change: 1 addition & 0 deletions python-312/pathlib_walk/musicians/readme.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A directory with jazz people
1 change: 1 addition & 0 deletions python-312/pathlib_walk/musicians/trumpet/armstrong.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Louie
1 change: 1 addition & 0 deletions python-312/pathlib_walk/musicians/trumpet/davis.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Miles
1 change: 1 addition & 0 deletions python-312/pathlib_walk/musicians/vocal/fitzgerald.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Ella
5 changes: 5 additions & 0 deletions python-312/quarters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import calendar
import itertools

for quarter in itertools.batched(calendar.Month, n=3):
print([month.name for month in quarter])
20 changes: 20 additions & 0 deletions python-312/sales.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import calendar

sales = {
calendar.JANUARY: 5,
calendar.FEBRUARY: 9,
calendar.MARCH: 6,
calendar.APRIL: 14,
calendar.MAY: 9,
calendar.JUNE: 8,
calendar.JULY: 15,
calendar.AUGUST: 22,
calendar.SEPTEMBER: 20,
calendar.OCTOBER: 23,
}
for month in calendar.Month:
if month in sales:
print(
f"{month.value:2d} {month.name:<10}"
f" {sales[month]:2d} {'*' * sales[month]}"
)
42 changes: 42 additions & 0 deletions python-312/typing/accounts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import random
from dataclasses import dataclass
from typing import Self, override


def generate_account_number() -> str:
"""Generate a random eleven-digit account number"""
account_number = str(random.randrange(10_000_000_000, 100_000_000_000))
return f"{account_number[:4]}.{account_number[4:6]}.{account_number[6:]}"


@dataclass
class BankAccount:
account_number: str
balance: float

@classmethod
def from_balance(cls, balance: float) -> Self:
return cls(generate_account_number(), balance)

def deposit(self, amount: float) -> None:
self.balance += amount

def withdraw(self, amount: float) -> None:
self.balance -= amount


@dataclass
class SavingsAccount(BankAccount):
interest: float

def add_interest(self) -> None:
self.balance *= 1 + self.interest / 100

@classmethod
@override
def from_balance(cls, balance: float, interest: float = 1.0) -> Self:
return cls(generate_account_number(), balance, interest)

@override
def withdraw(self, amount: float) -> None:
self.balance -= int(amount) if amount > 100 else amount
27 changes: 27 additions & 0 deletions python-312/typing/generic_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import Generic, TypeVar

T = TypeVar("T")


class Stack(Generic[T]):
def __init__(self) -> None:
self.stack: list[T] = []

def push(self, element: T) -> None:
self.stack.append(element)

def pop(self) -> T:
return self.stack.pop()


# %% Python 3.12

# class Stack[T]:
# def __init__(self) -> None:
# self.stack: list[T] = []
#
# def push(self, element: T) -> None:
# self.stack.append(element)
#
# def pop(self) -> T:
# return self.stack.pop()

0 comments on commit ec3309e

Please sign in to comment.