anofox-tabular Python package
Python wrapper for the anofox-tabular DuckDB extension — data quality, PII detection, email/phone validation, anomaly detection, diffing, money, and VAT primitives.
Installation
pip install anofox-tabular
Optional extras for DataFrame support:
pip install "anofox-tabular[pandas]" # adds pandas
pip install "anofox-tabular[polars]" # adds polars
pip install "anofox-tabular[pandas,polars]"
Quick start
import anofox
# In-memory database (extension downloaded automatically)
with anofox.connect() as conn:
# Email validation
print(conn.execute("SELECT anofox_tab_email_is_valid('hi@example.com', 'regex')").fetchone())
# Or use a locally built extension
conn = anofox.connect(
extension_path="/path/to/anofox_tabular.duckdb_extension"
)
With duckdb 2.0, a result of conn.execute() stays open until a fetch returns no more rows.
The anofox functions and conn.register(), conn.unregister() and conn.sql() run an open
result to its end first; conn.complete() does it explicitly (it does nothing on duckdb 1.5.x).
Python-native API
This block runs as is: it creates small sample tables first. Replace them with your own tables or DataFrames.
# needs the pandas extra: pip install "anofox-tabular[pandas]"
import pandas as pd
import anofox
from anofox import diff, pii, quality, validate
from anofox.validate import EmailRule, PhoneRule
conn = anofox.connect()
# ── Sample data (replace with your own tables) ───────────────────────
conn.execute("""
CREATE TABLE orders AS
SELECT i AS id, 20 + i % 13 AS amount,
CASE WHEN i % 4 = 0 THEN 'open' ELSE 'shipped' END AS status,
TIMESTAMP '2026-01-01' + INTERVAL (i) HOUR AS created_at
FROM range(1, 201) t(i)
""")
conn.execute("CREATE TABLE orders_v2 AS SELECT * FROM orders WHERE id <> 7")
# ── Email validation ──────────────────────────────────────────────────
print(validate.email_is_valid(conn, "hi@example.com")) # True
df = pd.DataFrame({"email": ["a@b.com", "bad-email", "c@d.org"]}, index=[10, 20, 30])
print(validate.email_is_valid(conn, df, column="email"))
# copy of df with an added 'email_is_valid' column; index and row order are kept,
# so the column can be assigned back:
df["ok"] = validate.email_is_valid(conn, df, column="email")["email_is_valid"]
# ── Phone validation ──────────────────────────────────────────────────
print(validate.phone_is_valid(conn, "+14155552671", region="US")) # True
print(validate.phone_format(conn, "+14155552671", "US", "INTERNATIONAL"))
phones = pd.DataFrame({"phone": ["4155552671", "01 42 68 53 00"], "country": ["US", "FR"]})
print(validate.phone_is_valid(conn, phones, column="phone", region_column="country"))
# region_column: the region of each row (instead of one region= for all rows).
# Without region= the setting anofox_tab_phonenumber_default_region applies (US by default).
print(validate.phone_format(conn, "12", "US")) # None: cannot be parsed
# ── Data quality ──────────────────────────────────────────────────────
print(quality.volume(conn, "orders", min_rows=100))
print(quality.null_rate(conn, "orders", "amount", max_null_rate=0.05)["message"])
print(quality.distinct_count(conn, "orders", "status", min_distinct=2, max_distinct=10))
print(quality.schema_check(conn, "orders", ["id", "amount", "created_at"]))
print(quality.volume(conn, df, min_rows=1)["status"]) # a DataFrame works too
# ── High-level profile ────────────────────────────────────────────────
print(conn.profile(df)) # pd.DataFrame with per-column metrics
# ── PII detection ─────────────────────────────────────────────────────
print(pii.pii_contains(conn, "Call me at +1-415-555-2671")) # True
print(pii.pii_detect(conn, "Email: test@example.com")) # [{"type": "EMAIL", ...}]
print(pii.pii_mask(conn, "test@example.com", strategy="redact"))
print(pii.pii_mask(conn, df, column="email")) # adds a 'pii_mask' column
print(pii.pii_mask(conn, df, column="email", replace=True)) # masks 'email' itself
print(pii.pii_scan_table(conn, "orders"))
print(pii.pii_mask(conn, df, column="email", types=["EMAIL", "PHONE"])) # no NER model: fast
# ── Diff ──────────────────────────────────────────────────────────────
print(diff.joindiff(conn, "orders", "orders_v2", primary_keys="id"))
# diff_type: 'added', 'removed', 'changed' (and 'unchanged' with include_unchanged=True)
print(diff.diff_schema(conn, "orders", "orders_v2"))
# one row per column: column_name, source_type, target_type, drift
# drift: 'same', 'added', 'removed' or 'retyped'
# ── Schema validation ─────────────────────────────────────────────────
contacts = pd.DataFrame({"email": ["a@b.com", "bad-email"], "phone": ["+49 30 901820", "123"]})
result = conn.validate(contacts, schema={
"email": EmailRule(mode="regex"),
"phone": PhoneRule(region="DE"),
})
print(result.passed) # False
print(result.failures) # DataFrame: column, row_id, value, rule
# ── Quality rules on a DataFrame ──────────────────────────────────────
checks = conn.quality_check(contacts, {
"volume": {"min_rows": 1, "max_rows": 10_000}, # min_rows, max_rows
"null_rate": {"column": "email", "max_null_rate": 0.05}, # column, max_null_rate
"distinct_count": {"column": "phone", "min_distinct": 2}, # column, min_distinct, max_distinct
})
print(checks.status) # 'pass' or 'fail'
print(checks.checks["null_rate"]["null_rate"])
DataFrames
- pandas and polars. Every function that takes a DataFrame takes either. Results that are
DataFrames use the input's library: a polars input gives a polars result, a pandas input
or a table name gives pandas. A value the extension cannot parse comes back as
None(a missing value in a DataFrame), like SQLNULL. A Series is not a DataFrame and raisesTypeError: passseries.to_frame()(withcolumn=series.namefor the row-wise helpers). - One type per column. A pandas
objectcolumn that mixes value types, such asstrandint(["+49 30 1234567", 4930765432]), cannot be copied into DuckDB and raisesTypeErrornaming the column and its types. Convert it first:df["phone"] = df["phone"].astype("string")(missing values stayNULL). - NaN and NULL. In a pandas DataFrame
NaNandNoneboth become SQLNULL. In a polars DataFrame onlynulldoes; a floatNaNstays a NaN value, sonull_rateandconn.profiledo not count it as missing. Usedf.fill_nan(None)to treat it as missing (see the Python guide). A single missing value (None,pd.NAorNaN) passed to a scalar helper ofanofox.validate,anofox.vat,anofox.moneyoranofox.piigivesNone, like SQLNULL. A text column that holds only missing values, such as thefloat64NaN column pandas reads for an empty CSV column, gives missing results in the row-wise helpers. - Column labels. The
anofox.quality,anofox.anomaly,anofox.profile,anofox.diffand PII table functions also take integer column labels (pandasread_csv(header=None)gives0,1, ...), also asid_column; the result names the column"0","1", ... . Where a list of columns is accepted (profile_table(columns=),profile_correlations,schema_check,joindiff(compare_columns=)), a single name such as"email"means that one column, not its characters. - Row-wise results (
email_is_valid,email_validate,phone_is_valid,phone_parse,phone_format,phone_region, theanofox.vatfunctions,make_money,pii_detect,pii_maskwithcolumn=) are a copy of the input plus one column. They keep the input's index (pandas) and row order, sodf["ok"] = ...["email_is_valid"]lines up. Forpii_maskandpii_mask_valuethat copy still holds the raw PII next to the mask;replace=Trueputs the masked values in the input column instead, so no raw value is left. - Table functions (
anofox.quality,anofox.anomaly,anofox.profile,anofox.diff,pii_scan_table,pii_audit_table,conn.profile,conn.quality_check) take a table name or a DataFrame. A DataFrame is copied into a temporary table for the call and dropped afterwards. On a connection to a database file (anofox.connect("my.db")) that copy is written to the file while the call runs. They also take apyarrow.Table(copied by DuckDB directly; the result is a pandas DataFrame, as for a table name). Any other object raisesTypeError; the row-wise helpers need a pandas or polars DataFrame (convert a pyarrow Table withtable.to_pandas()orpolars.from_arrow(table)). The functions that read through their own connection (anomaly detection, profiling, PII table scans) cannot see a temporary view, such as a DataFrame registered withconn.register(): its name raisesValueErrorwith the hint to pass the DataFrame itself. Error messages and result messages name such a copy "the DataFrame" (joindiff/hashdiff/diff_schema: "the source DataFrame", "the target DataFrame"), not its temporary table name. conn.profile(df_or_table)returns the columnscolumn,type,row_count,null_count,null_rate,distinct_count,distinct_rate;anofox.profile.profile_tablenames the first twocolumn_nameandcolumn_type(the others match).conn.profile(name)resolves a table name like a query does: with tables of the same name in several schemas it profiles the one the search path finds. Pass"schema.table"for another schema; an unknown table raisesduckdb.CatalogException.conn.validate(df, schema, include_nulls=False, id_column=None)returnsValidationResult(passed, failures).failureshas one row per failing value with the columnscolumn,row_id,valueandrule.row_idis the index label of the failing row for a pandas DataFrame and its 0-based row position for a polars DataFrame.id_column="customer_id"adds that column's value of each failing row (the business key) directly afterrow_id; a name that is no column of the DataFrame, or that is one of the four failure columns, raisesValueError. Each rule is anEmailRule(mode=...)or aPhoneRulefromanofox.validate; any other rule, such as the string"email", raisesTypeError.PhoneRule(region="DE")uses one region for all rows,PhoneRule(region_column="country")the region code in each row'scountrycolumn (passing both raisesValueError), andPhoneRule()the settinganofox_tab_phonenumber_default_region. A missing value (None,NaN) is skipped, as in SQL;include_nulls=Truereports it as a failure whose rule ends inmissing("email(regex) missing"). A schema key orregion_columnthat is not a column of the DataFrame raisesValueErrorlisting the columns.conn.quality_check(df, rules)supports the rulesvolume(keysmin_rows, default 1, andmax_rows),null_rate(column,max_null_rate, default 0.0) anddistinct_count(column,min_distinct, default 1, andmax_distinct). Any other rule name, a key the rule does not take ({"volume": {"min": 10}}) or a missingcolumnraisesValueErrorlisting the valid names. It returns aQualityResultwithstatus("pass"or"fail") andchecks(one result dict per rule);result["status"]works too.
Results
- The
anofox.qualitychecks return a dict with the call's parameters and every result column of the SQL function by name (status, the metric, the thresholds,message).DECIMALvalues are returned asfloat;_rawstill holds the raw result row (a DataFrame input is named "the DataFrame" there too, as inmessage). - Values are passed to DuckDB as bound parameters and column names are quoted, so any text
(
o'brien@example.ie) is safe to pass. numpy scalars (df["qty"].max(),numpy.float32,numpy.datetime64), numpy arrays andpandas.Timestampare passed as the equivalent Python values, also inconn.execute(...)parameters anddefine_checksparams. - Every function also takes a plain
duckdb.DuckDBPyConnectionwith the extension loaded in place of anAnofoxConnection. - The phone helpers need text: a number or a numeric DataFrame column raises
TypeError("phone numbers must be text ...; convert with astype(str)"); it is not converted, since a leading0may already be lost.money_from_centswith an integer outside theBIGINTrange raisesValueError. - The anomaly wrappers use the SQL defaults: every tuning parameter defaults to
None, is passed asNULL, and the extension applies its default (n_trees100,contamination0.1,eps0.5,min_pts5, ...). DBSCAN takes the SQL nameseps=andmin_pts=; the former namesepsilon=andmin_points=still work but give aDeprecationWarning(both names of one parameter raiseTypeError).isolation_forestandisolation_forest_mvtakeseed=for reproducible scores (isolation_forest_mvalsondim=). The per-row modes are"scores"(isolation forest),"clusters"(DBSCAN;"scores"is accepted too) and"outliers"(outlier tree); an unknownoutput_moderaisesValueError. Column lists can be a list or a comma-separated string ("amount, items"). A column whose name contains a comma cannot be selected and raisesValueError. - The per-row output (
"scores","clusters","outliers") of a pandas DataFrame carries the input's index labels, sodf["is_anomaly"] = scores["is_anomaly"]aligns; rows with aNULLfeature are not in the output and getNaN.row_idis the 1-based row number in the input. A polars output keeps the input's row order androw_id. A floatNaNis left out like aNULLby every detector, also in a polars DataFrame, so pandas and polars give the same result. A per-row output without rows has the same columns and dtypes as one with rows (outlier_tree'sconditionsstays anobjectcolumn, aListin polars). - The per-row output of
isolation_forestanddbscannames the scored columnvalue, as the SQL functions do, whatever the input column is called;id_column=adds a key to join on. email_validatewith a DataFrame adds oneemail_validatecolumn of dicts (valid,stage,reason,mx_hosts,smtp_debug), aStructcolumn in polars. Expand it withpd.DataFrame(out["email_validate"].dropna().tolist(), index=...)or polarsout.unnest("email_validate")(see the Python guide).- The return annotations name the scalar result (
Optional[bool],Optional[dict], ...) and, for a DataFrame input,pandas.DataFrame | polars.DataFrame. isolation_forestandisolation_forest_mvwarn (UserWarning) when 1 to 9 rows were scored (anomaly.MIN_ISOLATION_FOREST_ROWSis 10): so few rows score alike, and usually none is flagged. Pass at least 10 rows with values, or check so few values against a fixed range or a business rule (quality.compliance) instead.- The PII wrappers
pii_detect,pii_mask,pii_contains,pii_scan_tableandpii_audit_tabletaketypes=(a list or a comma-separated string) to detect only those types in the call; it setsanofox_pii_enabled_typesand restores it afterwards (pii.enabled_types(conn, types)does the same for awithblock). Without the NER types (NAME,ORGANIZATION,LOCATION,MISC) the NER model does not run, which makes masking many rows much faster. id_column=adds an input column to the per-row output; withoutput_mode="summary"it raisesValueError(id_column needs output_mode='scores','outliers'foroutlier_tree). Errors raised by DuckDB keep their type, without theLINE 1:excerpt of the wrapper's internal query.anofox qualitynames the input file in its errors.outlier_tree(..., output_mode="outliers")returnsconditionsas a list of dicts per outlier (polars:List(Struct)), each with the keyscolumn,type("numeric"or"categorical"),operator,value(numeric threshold, elseNone) andvalues(categories, elseNone). The SQL function returns the same conditions as JSON text.- With no scored row (
total_count0) theisolation_forestsummary hasavg_valueNone. A DataFrame column of onlyNoneraisesValueError("column 'amount' has no non-null values") inisolation_forest,isolation_forest_mv,dbscananddbscan_mv.
Module overview
| Module | Functions |
|---|---|
anofox.validate |
email_is_valid, email_validate, phone_is_valid, phone_parse, phone_format(conn, phone, region, format="E164") (fmt= is a deprecated alias), phone_region |
anofox.quality |
volume, null_rate, distinct_count, freshness, zscore, iqr, schema_check, regex_match, values_in_set, agg_check, duplicate_count, occurrence, match_rate, compliance, rel_count_change, metric_anomaly_iqr, rolling_values_in_set, define_checks, run_checks |
anofox.anomaly |
isolation_forest, isolation_forest_mv, dbscan, dbscan_mv, outlier_tree |
anofox.pii |
pii_detect, pii_mask, pii_mask_value, pii_contains, pii_scan_table, pii_audit_table, enabled_types |
anofox.diff |
joindiff, hashdiff, diff_schema |
anofox.profile |
profile_table, profile_summary, profile_correlations |
anofox.money |
make_money(conn, amount, currency) (or a DataFrame with column= and currency= / currency_column=), money_from_cents, is_valid_currency, currency_symbol, money_add, etc. |
anofox.vat |
make_vat, vat_is_valid, vat_is_valid_syntax, vat_validate (valid, country, reason), vat_exists (prefix check only), vat_split, vat_normalize, vat_format(conn, vat, style="plain"|"iso"), is_valid_vat_country, vat_is_eu_member, vat_country_name |
CLI
# Profile any file (colored table output)
anofox profile data.parquet
anofox profile data.csv --format json
# Quality checks
anofox quality data.parquet --volume-min 1000
anofox quality data.csv --null-max 0.05 --column email --format json
anofox quality exits with 0 when every check passes, 1 when a check fails and 2 when
the checks cannot run (invalid arguments, an unreadable file, an unknown column, a missing
extension binary); the error goes to stderr. With --format json, DECIMAL values are
written as JSON numbers and dates as ISO 8601 strings.
Supported formats: .parquet, .csv, .tsv, .json, .ndjson
pytest plugin
# Run with: pytest --anofox-check
import pytest
@pytest.mark.anofox_quality("orders", volume_min=100)
def test_orders_table_has_data(anofox_conn):
...
The anofox_conn session-scoped fixture is provided automatically. Tests skip if the extension is unavailable.
Extension resolution
The package resolves the extension in this order:
extension_pathargument toconnect()(path to a local binary)ANOFOX_EXT_PATHenvironment variable- DuckDB's own install:
INSTALL anofox_tabular FROM communityandLOAD anofox_tabular. DuckDB picks the build for its version and platform, caches it in~/.duckdb/extensions/and checks its signature. Withallow_unsigned=True(the default) DuckDB would skip that check, so the install and a signature-checked load run first on a separate in-memory database, and the connection then loads the checked file. - Cached binary in
~/.anofox/extensions/<duckdb version>/<platform>/ - Download from the DuckDB community registry, then the S3 mirror
(
https://get.erpl.io), both laid out as<base>/v<duckdb version>/<platform>/anofox_tabular.duckdb_extension.gz(duckdb1.5.6 downloads fromv1.5.6/,duckdb2.0.0 fromv2.0.0/)
Step 3 fails when there is no network, no community build for this DuckDB
version and platform, or the build does not load; then steps 4 and 5 run. A
non-default s3_base_url is an explicit choice of repository: steps 4 and 5
then run before step 3. If no source works, connect() raises a
RuntimeError that lists the error of each source.
Downloads exist only for DuckDB releases. With a pre-release, development or
post-release duckdb package (2.0.0rc1, 1.5.7.dev42, 1.5.6.post1)
connect() raises anofox.UnsupportedDuckDBVersionError (a RuntimeError)
before any download is attempted; install a released duckdb, or set
ANOFOX_EXT_PATH / extension_path to an extension built for that DuckDB.
The package declares duckdb>=1.0.0 without an upper bound: the extension is
published for each supported DuckDB release line (currently 1.5.x and 2.0).
Downloads in step 5 are verified against a .sha256 sidecar published next
to the archive. The S3 mirror publishes sidecars for every build; the
community registry does not, so by default these downloads come from the
mirror (step 3 needs no sidecar). Set ANOFOX_ALLOW_INSECURE_DOWNLOAD=1 to
accept archives without a sidecar.
Development
# Build the extension first (from the repository root)
GEN=ninja make release
# Create the dev environment
cd python
uv sync --extra dev
# Run tests
ANOFOX_EXT_PATH=../build/release/extension/anofox_tabular/anofox_tabular.duckdb_extension \
uv run pytest tests/ -v
# Loader/utils tests run without extension (no env var needed)
uv run pytest tests/test_loader.py tests/test_utils.py -v
License
Business Source License 1.1, the same as the extension. Production use is permitted, except offering it to third parties on a hosted or embedded basis. See LICENSE for the full terms.
Metadata
Release files for anofox-tabular 2026.10.31
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| anofox_tabular-2026.10.31.tar.gz | 162.3 kB | With provenance | Details for anofox_tabular-2026.10.31.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| anofox_tabular-2026.10.31-py3-none-any.whl | Python 3 | none | any | Details for anofox_tabular-2026.10.31-py3-none-any.whl |
Total release size: 232.3 kB
Release files / anofox_tabular-2026.10.31.tar.gz
| Download URL | anofox_tabular-2026.10.31.tar.gz |
|---|---|
| Size | 162.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
69a62d9b8509abffa7de160ce49fe324fc74092f021e3f1662629e9d649feec3
|
|
BLAKE2b-256 checksum How to use checksums |
06ad0a4e579ec676d36c6f2c0806673facaea61f025e828ae887c3dc2b891582
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 31, 2026.
Transparency logRelease files / anofox_tabular-2026.10.31-py3-none-any.whl
| Download URL | anofox_tabular-2026.10.31-py3-none-any.whl |
|---|---|
| Size | 70.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
240abed70a7048cae71a54bcfefe9ae0884556f1059c1e0e0083473c6cf2b79b
|
|
BLAKE2b-256 checksum How to use checksums |
7fd5248598f678314d7de4c2ec81b809e6e58c4a96856719726148fb15caec8f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 31, 2026.
Transparency logSecurity for anofox-tabular 2026.10.31
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for anofox_tabular-2026.10.31.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 31, 2026.
Transparency logA 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.