Skip to main content

opa-golib-python-bindings

Python bindings for the OPA Rego engine, embedding github.com/open-policy-agent/opa/v1/rego via a Go c-shared library and a stdlib-only ctypes wrapper.

Build

Requires Go >= 1.26 and Python >= 3.14.

make build   # builds src/opa_bindings/libopabridge.so
make test    # builds + runs pytest

Usage

from opa_bindings import OpaEngine

users = {"alice": {"role": "admin"}}

with OpaEngine() as engine:
    engine.add_policy("authz.rego", """
package authz

allow if lookup_user(input.user).role == "admin"
""")
    engine.add_data({"admin": ["alice"]}, path="roles")   # deep-merged; conflicts raise
    engine.register_function("lookup_user", lambda name: users.get(name))

    engine.eval_document("authz.allow", {"user": "alice"})  # -> True
    engine.eval_query("x = data.roles.admin[_]")            # -> [{"x": "alice"}]

Notes:

  • add_data deep-merges objects; identical values coexist, conflicting values raise OpaError(code="merge_conflict") naming the conflicting path.

  • register_function infers arity from the callable's signature. A *args function is variadic and is called from Rego with a single array argument: many(["a", "b"]) (OPA does not support variadic builtins with return values).

  • Builtin arguments and return values are JSON-compatible objects. A callback exception becomes an evaluation error; returning is fine.

  • An undefined document raises OpaUndefinedError.

  • Pass coverage=True to eval_document / eval_query to capture a coverage report (OPA's cover tracer) in engine.last_coverage: per-file covered / not_covered line ranges plus line counts and a coverage percentage over all added policies. Evaluating without coverage=True resets it to None.

  • Pass trace=True to capture the full evaluation trace in engine.last_trace: a list of event dicts (op, location, node, locals, ...) in evaluation order. locals holds the plugged variable bindings live at each step, so the value a statement produced is visible (e.g. {"x": 6} after x := input.n * 2); a false condition appears as a Fail event at its location. An undefined document still carries its trace — the main way to see which condition failed. Note that node shows the compiler-rewritten expression (temporaries like __local0__), a statement may appear multiple times (Redo on backtracking), and tracing slows evaluation, so keep it opt-in per call. Coverage only records which statements were evaluated; traces are how to see their results.

  • compile_filters partially evaluates a query and translates the residual policy into a data filter (OPA's Compile-API / data-filter machinery):

    engine.add_policy("filters.rego", """
    package filters
    
    include if input.fruits.colour == "green"
    include if {
        input.fruits.name == "banana"
        input.user == "admin"
    }
    """)
    engine.compile_filters(
        "data.filters.include",
        {"user": "admin"},              # known input
        unknowns=["input.fruits"],      # left symbolic
        target="sql", dialect="postgresql",
    )
    # -> {"query": "WHERE (fruits.colour = E'green' OR fruits.name = E'banana')",
    #     "masks": None}
    

    target="sql" (dialects postgresql, mysql, sqlserver, sqlite) yields a WHERE clause string; target="ucast" (dialects all, prisma, linq, or "") yields a UCAST condition dict (the ucast.json wire format). query is None when the policy can never match and ""/{} when it always matches. mappings renames tables/columns (e.g. {"fruits": {"$self": "fruit_table", "colour": "col"}}), and mask_rule names a rule evaluated to produce column masks (returned under "masks"). Residual conditions that cannot be expressed for the chosen target raise OpaError(code="compile_error").

    Unknown refs must have the shape input.<table>.<column> — exactly two segments after input, whatever the declared unknown boundary is, and for every target/dialect (ucast/all included; mappings cannot deepen it). So unknowns=["input.item"] permits only input.item.<column>, while the bare unknowns=["input"] permits input.<table>.<column>. Deeper refs like input.item.attrs.price.value fail with pe_fragment_error: invalid ref operand, so nested documents (e.g. an EAV entity with per-attribute type/value objects, or per-locale value objects) must be flattened into columns (input.attr.value_number, input.attr.value_de, ...). Dynamic column choice is fine as long as the key is known at compile time: input.attr[sprintf("value_%s", [input.locale])] resolves to a single column during partial evaluation.

  • Rego print(...) output is captured per evaluation: set engine.print_handler to a callable(message, location) to receive it (default: written to stderr); engine.last_prints holds the (message, location) pairs of the last eval.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

opa_golib_python_bindings-0.3.0.tar.gz (23.9 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_x86_64.whl (15.1 MB view details)

Uploaded Python 3manylinux: glibc 2.34+ x86-64

opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_aarch64.whl (13.7 MB view details)

Uploaded Python 3manylinux: glibc 2.34+ ARM64

opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_x86_64.whl (8.5 MB view details)

Uploaded Python 3macOS 11.0+ x86-64

opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_arm64.whl (7.8 MB view details)

Uploaded Python 3macOS 11.0+ ARM64

File details

Details for the file opa_golib_python_bindings-0.3.0.tar.gz.

File metadata

File hashes

Hashes for opa_golib_python_bindings-0.3.0.tar.gz
Algorithm Hash digest
SHA256 b787c28d6f72f26cf7320e6c97d900a9fc95b9442f31b31d39ef93c3d184035a
MD5 1122d4d0a85426982fe4d67b8b5612de
BLAKE2b-256 18867551fb3752d534eb901717e98a52071f8272a9930b8e3fa99a131a30bd11

See more details on using hashes here.

Provenance

The following attestation bundles were made for opa_golib_python_bindings-0.3.0.tar.gz:

Publisher: publish.yml on phi1010/opa-golib-python-bindings

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_x86_64.whl.

File metadata

File hashes

Hashes for opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_x86_64.whl
Algorithm Hash digest
SHA256 34b66f0ffe74239545b45f5ccf2011a5040e73ec61f52f2790e974ba70c2d433
MD5 fc9e38894599cebeae31d037b454fd16
BLAKE2b-256 b74f86f890f84714c1be97d61c5e7d9f61f04825fd4df1e823821dfddec98d29

See more details on using hashes here.

Provenance

The following attestation bundles were made for opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_x86_64.whl:

Publisher: publish.yml on phi1010/opa-golib-python-bindings

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_aarch64.whl.

File metadata

File hashes

Hashes for opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_aarch64.whl
Algorithm Hash digest
SHA256 e64bf1139a081c7defd7f69f3a0b0990232b8fc6b8daaa409beedd2e31c9db34
MD5 1441a0672f9670c59d6885c3bb8a78fa
BLAKE2b-256 7f0727094ce57808d85882866d7a931c7de690f8188e177638055456ae5ec306

See more details on using hashes here.

Provenance

The following attestation bundles were made for opa_golib_python_bindings-0.3.0-py3-none-manylinux_2_34_aarch64.whl:

Publisher: publish.yml on phi1010/opa-golib-python-bindings

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_x86_64.whl.

File metadata

File hashes

Hashes for opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_x86_64.whl
Algorithm Hash digest
SHA256 2124dc90fe41ffd163ff9e988d90bafd5f143bf209dfb5618aaf5afcf18a64e6
MD5 54eb878c7b4d646570b9e82b1d668f2e
BLAKE2b-256 1e7e86f467552ea4444b3cbc77944d45063ce7d56f84511b4ea3ba33cb640915

See more details on using hashes here.

Provenance

The following attestation bundles were made for opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_x86_64.whl:

Publisher: publish.yml on phi1010/opa-golib-python-bindings

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 ca24ee66c0f54d4a4ab3ee7b69c487117e41de44ffb39796ff8960669b87c426
MD5 9c9c532e2a0e347d3fb0fdd3b6d4b2e8
BLAKE2b-256 3be7b0346d1336a58aef3d5e0a7540d785a164d6e796786befd5b78887fcea25

See more details on using hashes here.

Provenance

The following attestation bundles were made for opa_golib_python_bindings-0.3.0-py3-none-macosx_11_0_arm64.whl:

Publisher: publish.yml on phi1010/opa-golib-python-bindings

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.3.0 This release

5 files

0.2.0

5 files

0.1.2

5 files

0.1.0

5 files

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