Skip to main content
pavise logo: a striped shield guarding a panda and a polar bear

pavise

Type-safe DataFrame validation with Python Protocols.
Describe your columns once with typing.Protocol, and get static type checking and runtime validation for pandas and polars.

PyPI version Python versions Tests Documentation Status License

Quick Start · Features · Installation · Usage · Supported Types · Performance · Documentation

🚀 Quick Start

pip install "pavise[pandas]"   # or "pavise[polars]"

Define a schema as a Protocol, validate at the boundary, and pass DataFrame[Schema] around with full type checking:

from typing import Annotated, Literal, Protocol

import pandas as pd

from pavise.pandas import DataFrame
from pavise.validators import Range, Unique


class UserSchema(Protocol):
    user_id: Annotated[int, Unique()]
    name: str
    age: Annotated[int, Range(0, 150)]
    plan: Literal["free", "pro"]


def count_pro_users(df: DataFrame[UserSchema]) -> int:
    return int((df["plan"] == "pro").sum())


raw_df = pd.DataFrame(
    {
        "user_id": [1, 2],
        "name": ["Alice", "Bob"],
        "age": [30, 25],
        "plan": ["free", "pro"],
    }
)
users = DataFrame[UserSchema](raw_df)  # validated at runtime
count_pro_users(users)  # type-checked by mypy / pyright

Bad data fails fast, with the rows that broke the rule:

DataFrame[UserSchema](
    pd.DataFrame(
        {
            "user_id": [1, 2, 3],
            "name": ["Alice", "Bob", "Carol"],
            "age": [30, -5, 200],
            "plan": ["free", "pro", "pro"],
        }
    )
)
ValidationError: Column 'age': values must be in range [0, 150]

Sample invalid values (showing first 2 of 2):
  Row 1: -5
  Row 2: 200

✨ Features

Feature What you get
🧩 Protocol schemas Schemas are plain typing.Protocol classes. No base class to inherit, no custom DSL
🔍 Static type checking DataFrame[Schema] works with mypy and pyright, so a wrong DataFrame is caught before you run anything
🦆 Structural subtyping Only the declared columns are checked and extra columns are ignored. DataFrame[Child] is accepted wherever DataFrame[Parent] is expected
✅ Runtime validation Check column types and values once at system boundaries, such as CSV files, databases and APIs
📏 Validators Range, Ge / Gt / Le / Lt, Unique, In, Regex, MinLen / MaxLen and Custom, attached with typing.Annotated
🔗 DataFrame-level checks @dataframe_check for rules across columns, such as start_at < end_at, and @unique for composite unique keys such as (user_id, date)
🔒 Strict mode strict=True rejects columns that are not in the schema
🐼 pandas & polars The same schema works on both backends, including polars LazyFrame
💬 Readable errors Errors name the column and show sample rows with the invalid values

Why "pavise"?

A pavise was a large shield used by medieval crossbowmen, big enough to cover the whole body. Like its namesake, this library is a shield for your data: whether your datasets are small or big, pavise protects your code with type safety and validation. The logo shows that shield, striped and split in two, with a panda on one half and a polar bear on the other: it guards your pandas and polars DataFrames.

📦 Installation

# For pandas support
pip install "pavise[pandas]"

# For polars support
pip install "pavise[polars]"

# For both
pip install "pavise[all]"

pavise supports Python 3.10 and later. The pandas backend requires pandas 2.2.0 or later, and the polars backend requires polars 1.0.0 or later.

📖 Usage

The full guide is at pavise.readthedocs.io.

pandas and polars

Import DataFrame from pavise.pandas or pavise.polars. The schema is the same for both:

from typing import Protocol

import pandas as pd
import polars as pl

from pavise.pandas import DataFrame as PandasDataFrame
from pavise.polars import DataFrame as PolarsDataFrame


class UserSchema(Protocol):
    name: str
    age: int


pandas_users = PandasDataFrame[UserSchema](
    pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 17]})
)
polars_users = PolarsDataFrame[UserSchema](
    pl.DataFrame({"name": ["Alice", "Bob"], "age": [30, 17]})
)


def adults(df: PolarsDataFrame[UserSchema]) -> PolarsDataFrame[UserSchema]:
    return PolarsDataFrame[UserSchema](df.filter(pl.col("age") >= 18))


adults(polars_users)

For polars, LazyFrame[Schema] checks column names and types when it is created and checks values on collect(). See the pandas and polars backend guides.

Structural subtyping

A schema only lists the columns a function needs. A DataFrame with more columns can be passed in:

from typing import Protocol

import pandas as pd

from pavise.pandas import DataFrame


class UserSchema(Protocol):
    name: str


class UserWithEmailSchema(Protocol):
    name: str
    email: str


def greet(df: DataFrame[UserSchema]) -> None:
    for name in df["name"]:
        print(f"Hello, {name}!")


df = DataFrame[UserWithEmailSchema](
    pd.DataFrame({"name": ["Alice"], "email": ["alice@example.com"]})
)
greet(df)  # OK: UserWithEmailSchema has every column of UserSchema

Pass strict=True to reject extra columns instead:

DataFrame[UserSchema](df, strict=True)
# ValidationError: Strict mode: unexpected columns ['email']

Validators

Attach validators to a column with typing.Annotated:

from typing import Annotated, Protocol

import pandas as pd

from pavise.pandas import DataFrame
from pavise.validators import Ge, Gt, Range, Regex


class OrderSchema(Protocol):
    customer_email: Annotated[str, Regex(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")]
    price: Annotated[float, Ge(0)]
    quantity: Annotated[int, Gt(0)]
    discount: Annotated[float, Range(0, 1)]


DataFrame[OrderSchema](
    pd.DataFrame(
        {
            "customer_email": ["alice@example.com"],
            "price": [9.5],
            "quantity": [0],  # must be > 0
            "discount": [0.1],
        }
    )
)
# ValidationError: Column 'quantity': values must be > 0
Validator Description
Range(min, max) Values within [min, max]
Ge(value) / Gt(value) Values >= value / > value
Le(value) / Lt(value) Values <= value / < value
Unique() No duplicate values
In(values) Values within an allowed set
Regex(pattern) Strings fully matching a regular expression (re.fullmatch)
MinLen(n) / MaxLen(n) String length bounds
Custom(func, message) Custom validation function

Range, Ge, Gt, Le and Lt accept numbers as well as date, datetime, time, timedelta and Decimal bounds. See the validators guide for details.

DataFrame-level checks

Use the @dataframe_check class decorator for rules that span several columns:

from datetime import datetime
from typing import Protocol

import pandas as pd

from pavise.checks import dataframe_check
from pavise.pandas import DataFrame


@dataframe_check(lambda df: df["start_at"] < df["end_at"], name="start_before_end")
class EventSchema(Protocol):
    start_at: datetime
    end_at: datetime


df = pd.DataFrame(
    {
        "start_at": pd.to_datetime(["2024-01-01", "2024-01-05"]),
        "end_at": pd.to_datetime(["2024-01-02", "2024-01-03"]),
    }
)
DataFrame[EventSchema](df)
# ValidationError: DataFrame check 'start_before_end' failed
#
# Sample invalid values (showing first 1 of 1):
#   Row 1: {'start_at': Timestamp('2024-01-05 00:00:00'), 'end_at': Timestamp('2024-01-03 00:00:00')}

The check function receives the backend's native DataFrame and returns a boolean per row (pd.Series, pl.Series or pl.Expr) or a single bool. Checks run after column validation, and polars.LazyFrame runs them on collect(). The decorator does not add members to the Protocol, so structural subtyping keeps working.

Optional values, unions and literals

from typing import Literal, Optional, Protocol, Union

import pandas as pd

from pavise.pandas import DataFrame, NotRequiredColumn


class TicketSchema(Protocol):
    code: Union[int, str]  # int or str
    status: Literal["open", "closed"]  # only these values
    assignee: Optional[str]  # may contain None
    note: NotRequiredColumn[str]  # the column may be absent


df = pd.DataFrame(
    {
        "code": [1, "B-2"],
        "status": ["open", "closed"],
        "assignee": ["alice", None],
    }
)
DataFrame[TicketSchema](df)  # OK: 'note' is not required

🧾 Supported Types

Kind Types
Basic int, float, str, bool
Date / time datetime, date, timedelta
Generic Optional[T], Union[T1, T2, ...] (Union[int, str, None] for nullable unions), Literal[...], NotRequiredColumn[T]
pandas pd.CategoricalDtype, pd.Int64Dtype and other extension dtypes
polars pl.Categorical, pl.Int64 and other polars data types

⚡ Performance

pavise checks only what the schema asks for and builds no error report until a check fails. Compared with pandera running the same checks (lazy=False, no coercion):

pavise pandera
pandas, 7 columns, 10 rows 0.34 ms 1.82 ms
pandas, 7 columns, 1,000,000 rows 50 ms 240 ms
polars, 7 columns, 10 rows 0.13 ms 2.7 ms
polars, 7 columns, 1,000,000 rows 1.0 ms 4.3 ms
polars, str with length and regex checks, 1,000,000 rows 3.6 ms 4.6 ms

Where the difference comes from:

  • Fixed cost per call. pandera runs every check through a general pipeline: it copies each column's schema component, resolves its config for every check, and prepares failure cases even for checks that pass. On polars it runs two or three queries per check.
  • pandas. pandera copies the input frame by default (inplace=False) and checks the type of an object string column with a Python function per element. pavise does not copy, and uses pandas.api.types.infer_dtype.
  • polars. pavise evaluates all value checks of a frame in one select. On polars 2.0, from 50,000 rows on, it runs that as a lazy query, which spreads over all cores.

Where they are about even:

  • Composite unique keys (UniqueKeys): finding the duplicates takes most of the time in both.
  • polars 1.x on large string columns: lazy queries run on one core there, so regex and In checks take about the same time in both.

Notes:

  • pandera can collect every error (lazy=True), return failure cases as a DataFrame, drop invalid rows and coerce types. pavise stops at the first error. Part of pandera's cost pays for those features.
  • pandera validates only the schema of a polars LazyFrame by default. pavise checks values when the LazyFrame is collected.

Measured on an AMD Ryzen 9 7940HS (8 cores, 16 threads), Linux, Python 3.14.6, pandas 2.3.3, polars 2.0.0 and pandera 0.36.0. To reproduce:

uv run --with 'pandera[polars]' python benchmarks/bench_overhead.py \
    --backend pandas --backend polars \
    --scenario "wide 7 cols" --scenario "MinLen+MaxLen+Regex" \
    --rows 10 --rows 1000000

See benchmarks/ for every scenario and the pandera schema each one is compared with.

🛠️ Development

# Install with dev dependencies (includes both pandas and polars)
uv pip install -e ".[dev]"

# Run all tests
uv run pytest

# Run tests for specific backend
uv run pytest tests/test_pandas/
uv run pytest tests/test_polars/

Documentation examples

tests/test_docs_examples.py runs every Python code block in README.md and docs/**/*.rst. Blocks on the same page share one namespace, top to bottom. Put one of these comments right before a block to change how it is run or checked (they are not rendered):

reStructuredText Markdown Effect
.. example-setup + indented code <!-- example-setup ... --> Hidden code run at that point (e.g. to define df)
.. example-raises: ValidationError <!-- example-raises: ValidationError --> The next block must raise that exception
.. example-skip <!-- example-skip --> Do not run the next block (e.g. it needs a database or network)
.. example-output + text block <!-- example-output --> + text block The text block must equal what the previous block prints, or ExceptionName: message for an example-raises block

Testing with tox

# Run tests for all Python versions and backends
tox

# Run tests for specific environment
tox -e py312-pandas    # Test pandas backend with Python 3.12
tox -e py312-polars    # Test polars backend with Python 3.12
tox -e py312-all       # Test both backends with Python 3.12

# Run linting
tox -e lint

# Run type checking
tox -e type

# Available Python versions: py310, py311, py312, py313, py314
# Available backends: pandas, polars, all

Metadata

Release files for pavise 0.3.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pavise 0.3.2
File Size Uploaded Provenance Actions
pavise-0.3.2.tar.gz 223.8 kB Without provenance Details for pavise-0.3.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pavise 0.3.2
File Interpreter ABI Platform Actions
pavise-0.3.2-py3-none-any.whl Python 3 none any Details for pavise-0.3.2-py3-none-any.whl

Total release size: 283.1 kB

Release files / pavise-0.3.2.tar.gz

Download URL pavise-0.3.2.tar.gz
Size 223.8 kB
Tags Source
SHA-256 checksum
How to use checksums
084282ad70b5f8b2c5c86d2231fdc9d4e044e9bf964bc96d14bb43937c14a6d3
BLAKE2b-256 checksum
How to use checksums
952fdea4696291fad73088c2a6d77a84f44528c017a1296cbb9d2436dbcbf1b9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pavise-0.3.2-py3-none-any.whl

Download URL pavise-0.3.2-py3-none-any.whl
Size 59.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d463ce9c4294d288f12c461c91061f2771c9c1143a38de613d81f3622f16d600
BLAKE2b-256 checksum
How to use checksums
e8c1ae1941027bf514803d21032bd8887ce5f672428ca498402c85655c353922
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pavise 0.3.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page