Examples¶
Shapix Tour Notebook¶
The tour notebook is still the broadest runnable walkthrough in the repository:
- basic
@beartypeusage - named dimensions and cross-argument consistency
- return checking
- fixed, variadic, broadcastable, anonymous, and symbolic dimensions
Value(...)- checker-only alias tricks for fixed literal dims and other runtime-only shape tokens
- custom array types
- explicit memo helpers
- tree annotations
Example 1: Plain @beartype¶
import numpy as np
from beartype import beartype
from shapix import C, N
from shapix.numpy import F32
@beartype
def normalize(x: F32[N, C]) -> F32[N, C]:
return x / x.sum(axis=1, keepdims=True)
normalize(np.ones((4, 3), dtype=np.float32)) # OK
normalize(np.ones((4,), dtype=np.float32)) # Raises
Example 2: @shapix.check when plain @beartype is not enough¶
import shapix
from beartype import beartype
from shapix import Value
from shapix.numpy import F32
@shapix.check
@beartype
async def make_batch(size: int) -> F32[Value("size")]: # type: ignore[valid-type]
...
Use this pattern when:
- extra decorators or framework wrappers make frame detection brittle
Value(...)needs an explicit memo scope acrossawait- you want one decorator that applies both memo handling and
BeartypeConf
Example 3: Custom dimensions that stay checker-friendly¶
import typing as tp
from beartype import beartype
from shapix import Dimension, N
from shapix.numpy import F32, I64
if tp.TYPE_CHECKING:
type Vocab = int
type Embed = int
else:
Vocab = Dimension("Vocab")
Embed = Dimension("Embed")
@beartype
def embed_lookup(tokens: I64[N], table: F32[Vocab, Embed]) -> F32[N, Embed]:
return table[tokens]
Example 4: Tree leaf and structure checking¶
from beartype import beartype
from shapix import N, T
from shapix.numpy import F32
from shapix.optree import Tree
@beartype
def accumulate(params: Tree[F32[N], T],
grads: Tree[F32[N], T]) -> Tree[F32[N]]: # type: ignore[valid-type]
...
Use leaf-only Tree[F32[N]] when you want cleaner static typing. Add structure symbols like T when you want runtime structure equality too.