# Python
## `dict.get()` vs `[]`
```python
d.get("key", default) # returns default if missing (None if omitted)
d["key"] # raises KeyError if missing
```
## UTF-8 Mode
```bash
python3 -X utf8
```
Forces UTF-8 encoding regardless of locale settings.
## Virtual Environments
```bash
python3 -m venv .venv # create
python3 -m venv --system-site-packages . # inherit system packages
```
## Unpacking Argument Lists
```python
values = [1, 2, 3]
foo(*values) # positional unpacking
foo(**{"a": 1}) # keyword unpacking
```
[Docs: Unpacking Argument Lists](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists)
## Type Annotations for `*args` and `**kwargs`
Annotate the type of a single element, not the collection:
```python
def foo(*args: int, **kwargs: str):
...
```
This means each positional arg is `int` and each keyword arg value is `str`.
If you need a fixed number of arguments, use explicit parameters instead:
```python
def foo(first: int, second: int | None = None):
...
```
## py_compile — Syntax Validation
Compile without executing — catches syntax errors before runtime:
```bash
python -m py_compile script.py # single file (no output = success)
python -m compileall . # all .py files recursively
```
Catches syntax errors, indentation errors, and invalid keywords. Does **not** catch runtime errors, logic errors, or missing dependencies.
## Frozen Dataclasses
A "frozen" dataclass is immutable — instances cannot be modified after creation, similar to `frozenset` vs `set`:
```python
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(1.0, 2.0)
p.x = 3.0 # raises FrozenInstanceError
```
See: [StackOverflow](https://stackoverflow.com/questions/66194804/what-does-frozen-mean-for-dataclasses)
## atexit — Cleanup on Exit
Register functions to run automatically at interpreter termination, in reverse order:
```python
import atexit
atexit.register(cleanup_function)
```
[Docs: atexit](https://docs.python.org/3/library/atexit.html)
---
See also: [[uv]], [[Ruff]], [[ty]], [[Python Code Quality]]