diff --git a/python-312/README.md b/python-312/README.md index ea8679a4be..791570268f 100644 --- a/python-312/README.md +++ b/python-312/README.md @@ -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/) @@ -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. @@ -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) @@ -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: [martin@realpython.com](martin@realpython.com) diff --git a/python-312/comprehension_benchmark.py b/python-312/comprehension_benchmark.py new file mode 100644 index 0000000000..7915273b72 --- /dev/null +++ b/python-312/comprehension_benchmark.py @@ -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) diff --git a/python-312/error-messages/shapes.py b/python-312/error-messages/shapes.py new file mode 100644 index 0000000000..3a32ddb7eb --- /dev/null +++ b/python-312/error-messages/shapes.py @@ -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() diff --git a/python-312/pathlib_walk.py b/python-312/pathlib_walk.py new file mode 100644 index 0000000000..94aee3d29d --- /dev/null +++ b/python-312/pathlib_walk.py @@ -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) diff --git a/python-312/pathlib_walk/musicians/readme.txt b/python-312/pathlib_walk/musicians/readme.txt new file mode 100644 index 0000000000..dce27e1b71 --- /dev/null +++ b/python-312/pathlib_walk/musicians/readme.txt @@ -0,0 +1 @@ +A directory with jazz people diff --git a/python-312/pathlib_walk/musicians/trumpet/armstrong.txt b/python-312/pathlib_walk/musicians/trumpet/armstrong.txt new file mode 100644 index 0000000000..cb86af6ce8 --- /dev/null +++ b/python-312/pathlib_walk/musicians/trumpet/armstrong.txt @@ -0,0 +1 @@ +Louie diff --git a/python-312/pathlib_walk/musicians/trumpet/davis.txt b/python-312/pathlib_walk/musicians/trumpet/davis.txt new file mode 100644 index 0000000000..8488b04bb0 --- /dev/null +++ b/python-312/pathlib_walk/musicians/trumpet/davis.txt @@ -0,0 +1 @@ +Miles diff --git a/python-312/pathlib_walk/musicians/vocal/fitzgerald.txt b/python-312/pathlib_walk/musicians/vocal/fitzgerald.txt new file mode 100644 index 0000000000..64f51c4c6a --- /dev/null +++ b/python-312/pathlib_walk/musicians/vocal/fitzgerald.txt @@ -0,0 +1 @@ +Ella diff --git a/python-312/quarters.py b/python-312/quarters.py new file mode 100644 index 0000000000..45cc70dc50 --- /dev/null +++ b/python-312/quarters.py @@ -0,0 +1,5 @@ +import calendar +import itertools + +for quarter in itertools.batched(calendar.Month, n=3): + print([month.name for month in quarter]) diff --git a/python-312/sales.py b/python-312/sales.py new file mode 100644 index 0000000000..585dc9cf6c --- /dev/null +++ b/python-312/sales.py @@ -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]}" + ) diff --git a/python-312/typing/accounts.py b/python-312/typing/accounts.py new file mode 100644 index 0000000000..f6d923db0a --- /dev/null +++ b/python-312/typing/accounts.py @@ -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 diff --git a/python-312/typing/generic_stack.py b/python-312/typing/generic_stack.py new file mode 100644 index 0000000000..a829481327 --- /dev/null +++ b/python-312/typing/generic_stack.py @@ -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()