Metadata-Version: 2.4
Name: annassert
Version: 0.1.1
Summary: Convert Python assertions to type annotations and back
Requires-Python: >=3.10
Requires-Dist: annotated-types>=0.7
Requires-Dist: libcst>=1.4
Description-Content-Type: text/markdown

# AnnAssert

`annassert` (**Ann**otated **Assert**ions) is a Python library and CLI tool that turns assertions into annotations, and vice versa.

Go from here:

```python
def repeat(s, n):
    """Repeat string s n times."""
    assert isinstance(s, str) and len(s) > 0
    assert isinstance(n, int) and n >= 0 and n <= 100
    return s * n
```

To there:

```python
def repeat(s: Annotated[str, MinLen(1)], n: Annotated[int, Ge(0), Le(100)]):
    """Repeat string s n times."""
    assert len(s) >= 1
    assert n >= 0 and n <= 100
    return s * n
```

And enjoy your type-checker superpowers!

# How to use 

Install with `pip` or `ruff`, then:

```bash
# by default, adds annotations AND assertions
annassert path/to/your/code.py

# diff mode
annassert --diff path/to/your/code.py

# check mode
annassert --check path/to/your/code.py
```

# Supported conversions

| Assert clause | Annotation | Notes |
|---|---|---|
| `x > v` | `Annotated[T, Gt(v)]` | |
| `x >= v` | `Annotated[T, Ge(v)]` | |
| `x < v` | `Annotated[T, Lt(v)]` | |
| `x <= v` | `Annotated[T, Le(v)]` | |
| `len(x) >= v` | `Annotated[T, MinLen(v)]` | |
| `len(x) <= v` | `Annotated[T, MaxLen(v)]` | |
| `x % v == 0` | `Annotated[T, MultipleOf(v)]` | |
| `x.ndim == n` | `Shaped[T, "_ … _"]` (n dims) | jaxtyping |
| `x.shape[i] == v` | `Shaped[T, "… v …"]` | jaxtyping, integer `v` only |
| *(type checker)* | `Float[T, s]`, `Int[T, s]`, … | jaxtyping dtype — no runtime assert |
| *(type checker)* | `x: T` | base type — no runtime assert |

> Note: We have only partial support for named jaxtyping axes (e.g. `"batch seq d_model"`). They are translated to weaker assertions (`assert x.ndims == 4`)

# Why ?

This project was created during the [Apart Research Software security hackathon](https://apartresearch.framer.website/sprints), as part of a broader effort to drastically improve the quality of python research code.
