AgentSheet
Back
🐍

Python

languagescriptingbackend

Data Types

TypeExampleNotes
str"hello", 'world'Immutable
int42, 1_000_000Arbitrary precision
float3.14, 1e-3
boolTrue, FalseSubclass of int
list[1, 2, 3]Mutable, ordered
tuple(1, 2) or 1, 2Immutable, ordered
dict{"a": 1, "b": 2}Key-value, keys hashable
set{1, 2, 3}Mutable, unique, unordered
# Type checking
type(x) == int
isinstance(x, (int, float))

Strings

s = "Hello World"
s[0], s[-1], s[1:5], s[::-1]  # H, d, ello, dlroW olleH
s.upper(), s.lower(), s.strip(), s.split()
s.replace("old", "new"), s.startswith("He"), s.endswith("ld")
s.join(["a", "b"])  # "a" + s + "b"

f-strings:

f"{name} is {age}"
f"{x:.2f}"           # 2 decimal places
f"{n:b}"             # binary
f"{obj!r}"           # repr()

Comprehensions

# List
[x**2 for x in range(5)]                    # [0, 1, 4, 9, 16]
[x for x in lst if x > 0]

# Dict
{k: v*2 for k, v in d.items()}
{i: i**2 for i in range(5)}

# Set
{x % 3 for x in range(10)}

# Nested
[[i*j for j in range(3)] for i in range(3)]

Functions

def f(a, b=0, *args, **kwargs):
    pass

# *args: tuple of extra positional args
# **kwargs: dict of extra keyword args

# Lambda
lambda x: x * 2
sorted(lst, key=lambda x: x[1])

# Decorator
def deco(f):
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapper

@deco
def foo(): pass

Classes

class Foo:
    def __init__(self, x):
        self.x = x

    def __str__(self): return f"Foo({self.x})"
    def __repr__(self): return f"Foo(x={self.x})"
    def __len__(self): return len(self.x)
    def __getitem__(self, i): return self.x[i]

class Bar(Foo):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

Dataclasses:

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float = 0.0

File I/O

# Read
with open("file.txt") as f:
    content = f.read()
lines = f.readlines()

# Write
with open("out.txt", "w") as f:
    f.write("text\n")

# Modes: r, w, a, r+, rb, wb

Error Handling

try:
    risky()
except ValueError as e:
    handle(e)
except (TypeError, KeyError):
    pass
except Exception:
    raise
else:
    # runs if no exception
finally:
    # always runs
    cleanup()

Built-in Functions

FunctionExample
maplist(map(str.upper, lst))
filterlist(filter(lambda x: x > 0, lst))
ziplist(zip(a, b)) β†’ [(a0,b0), (a1,b1), ...]
enumeratefor i, x in enumerate(lst):
sortedsorted(lst, key=fn, reverse=True)
rangerange(5), range(1, 10, 2)
sum, min, maxsum(lst), min(lst)
any, allany(lst), all(lst)
abs, round, divmodabs(-1), round(3.5)

Standard Library

ModuleCommon use
osos.getcwd(), os.listdir(), os.environ
syssys.argv, sys.exit(), sys.path
jsonjson.loads(s), json.dumps(obj)
pathlibPath("a/b").read_text(), .exists(), .glob("*.py")
datetimedatetime.now(), timedelta(days=1)
collectionsCounter, defaultdict, deque
itertoolschain, cycle, combinations, permutations
from pathlib import Path
Path("data.json").read_text()
Path("out").write_text("content")

from collections import Counter, defaultdict
Counter("hello")  # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
dd = defaultdict(list)

Type Hints

def greet(name: str) -> str:
    return f"Hello, {name}"

def process(items: list[int], config: dict[str, Any] | None = None) -> None:
    pass

from typing import Optional, List, Dict, Union, Any, Callable
x: Optional[int] = None
callback: Callable[[int, str], bool]