Python

Quickstart (venv + run)

bash
python -m venv .venv
source .venv/bin/activate
python -c 'print("hello")'

Project setup (requirements.txt)

text
# requirements.txt
requests==2.*

Virtualenv + run

bash
python -m venv .venv
source .venv/bin/activate
python main.py

Dataclass

python
from dataclasses import dataclass

@dataclass(frozen=True)
class User:
    id: str
    email: str

Typing + async

python
from typing import Any

async def fetch_json(url: str) -> dict[str, Any]:
    import aiohttp
    async with aiohttp.ClientSession() as s:
        async with s.get(url) as r:
            r.raise_for_status()
            return await r.json()

Variables + basic types

python
name = "Sam"   # str
n = 123          # int
pi = 3.14        # float
ok = True        # bool
nothing = None   # NoneType

Datatypes (list, tuple, dict, set)

python
xs = [1, 2, 3]           # list
pair = ("a", 1)          # tuple
m = {"a": 1, "b": 2}     # dict
s = {1, 2, 3}            # set

Iteration (for, enumerate, dict items)

python
xs = ["a", "b"]
for i, x in enumerate(xs):
    print(i, x)

m = {"a": 1}
for k, v in m.items():
    print(k, v)

Comprehensions

python
xs = [1, 2, 3]
ys = [x * 2 for x in xs]
ss = {x for x in xs if x % 2 == 1}
mm = {x: x * 10 for x in xs}

Functions (defaults, *args, **kwargs)

python
def greet(name: str, prefix: str = "hi") -> str:
    return f"{prefix} {name}"

def f(*args: int, **kwargs: str):
    print(args, kwargs)

Classes (init + property)

python
class User:
    def __init__(self, email: str):
        self._email = email

    @property
    def email(self) -> str:
        return self._email