CodeSampleX

Пример

polars-runtime-32 1.43.2: Construct, inspect, and stream-serialize native Polars expressions using PyExpr, col, lit, and when in polars-runtime-32

Проверенный пример — pypi polars-runtime-32 1.43.2: Construct, inspect, and stream-serialize native Polars expressions using PyExpr, col, lit, and when in…

sha256:9c2cefb58fbf7782c12166c67d9b70e65d0307bb2f902cbaffd7293d7e6b0bc5

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-27

Кейс

HOW
Цель
Construct, inspect, and stream-serialize native Polars expressions using PyExpr, col, lit, and when in polars-runtime-32
Пакеты
Символы
  • _polars_runtime.PyExpr
  • _polars_runtime.col
  • _polars_runtime.lit
  • _polars_runtime.when
Создан
2026-08-27T20:37:34Z

Контракт

  1. assert pr.lit(42) raises TypeError requiring allow_object and is_scalar positional arguments
  2. assert pr.col('price').meta_is_column() is True and meta_root_names() == ['price']
  3. assert (pr.col('price') * pr.lit(1.1, False, True)).alias('total_price').meta_output_name() == 'total_price'
  4. assert meta_undo_aliases() reverts aliased expression output name back to 'price'
  5. assert meta_is_column_selection(allow_aliasing) and meta_is_literal(allow_aliasing) require explicit boolean flag
  6. assert when/then/otherwise builds conditional PyExpr reflecting predicate root names
  7. assert PyExpr.serialize_json and serialize_binary accept stream buffers and deserialize to equal expressions via meta_eq

Файлы

  • NOTES.md
  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • test/contract.py

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Native Expression Construction and Serialization in polars-runtime-32

This sample documents the native Python expression APIs (`PyExpr`, `col`, `lit`, `when`) provided by `_polars_runtime_32._polars_runtime`.

The exact release pinned is `1.43.2`.

## Observed Behaviour

1. **Literal Construction Signature**:
   - `pr.lit()` requires three positional arguments: `(value, allow_object, is_scalar)`.
   - Passing a single argument such as `pr.lit(42)` raises `TypeError: lit() missing 2 required positional arguments: 'allow_object' and 'is_scalar'`.

2. **Meta Predicate Parameters**:
   - Predicates such as `PyExpr.meta_is_column_selection()` and `PyExpr.meta_is_literal()` require an explicit boolean argument `allow_aliasing`.
   - An aliased literal (`pr.lit(100, False, True).alias("x")`) returns `False` for `meta_is_literal(False)` and `True` for `meta_is_literal(True)`.

3. **Stream-based Serialization**:
   - `PyExpr.serialize_json()` and `PyExpr.serialize_binary()` do not return strings or byte arrays directly; they require a writable Python stream object (such as `io.BytesIO`). Calling them without an argument raises `TypeError: PyExpr.serialize_json() missing 1 required positional argument: 'py_f'`.
   - Symmetrically, `pr.PyExpr.deserialize_json(buf)` and `pr.PyExpr.deserialize_binary(buf)` read from stream objects, producing expressions structurally identical via `meta_eq()`.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Construct, inspect, and stream-serialize native Polars expressions using PyExpr, col, lit, and when in polars-runtime-32
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/polars-runtime-32@1.43.2
Demonstrate these symbols/APIs:
  - _polars_runtime.PyExpr
  - _polars_runtime.col
  - _polars_runtime.lit
  - _polars_runtime.when

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:de58e210db09d28dc7f51cfa548231171baf9099f243c74c6c638e91d0f68e9c","contract":["assert pr.lit(42) raises TypeError requiring allow_object and is_scalar positional arguments","assert pr.col('price').meta_is_column() is True and meta_root_names() == ['price']","assert (pr.col('price') * pr.lit(1.1, False, True)).alias('total_price').meta_output_name() == 'total_price'","assert meta_undo_aliases() reverts aliased expression output name back to 'price'","assert meta_is_column_selection(allow_aliasing) and meta_is_literal(allow_aliasing) require explicit boolean flag","assert when/then/otherwise builds conditional PyExpr reflecting predicate root names","assert PyExpr.serialize_json and serialize_binary accept stream buffers and deserialize to equal expressions via meta_eq"],"goal":"Construct, inspect, and stream-serialize native Polars expressions using PyExpr, col, lit, and when in polars-runtime-32","kind":"HOW","packages":["pkg:pypi/polars-runtime-32@1.43.2"],"schemaVersion":1,"symbols":["_polars_runtime.PyExpr","_polars_runtime.col","_polars_runtime.lit","_polars_runtime.when"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/polars-runtime-32@1.43.2"],"schemaVersion":1,"subject":"pkg:pypi/polars-runtime-32@1.43.2","symbols":["_polars_runtime.PyExpr","_polars_runtime.col","_polars_runtime.lit","_polars_runtime.when"],"verifierAdapter":"python@1"}
requirements.txt
polars-runtime-32==1.43.2
spec.json
{
  "schemaVersion": 1,
  "goal": "Construct, inspect, and stream-serialize native Polars expressions using PyExpr, col, lit, and when in polars-runtime-32",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/polars-runtime-32@1.43.2"
  ],
  "symbols": [
    "_polars_runtime.PyExpr",
    "_polars_runtime.col",
    "_polars_runtime.lit",
    "_polars_runtime.when"
  ]
}
test/contract.py
import io
import _polars_runtime_32._polars_runtime as pr


def test_lit_argument_shape():
    # 1. pr.lit requires (value, allow_object, is_scalar)
    try:
        pr.lit(42)
        raise AssertionError("pr.lit(42) should have raised TypeError")
    except TypeError as exc:
        assert "missing 2 required positional arguments: 'allow_object' and 'is_scalar'" in str(exc)

    lit_expr = pr.lit(42, False, True)
    assert lit_expr.meta_is_literal(False) is True
    assert lit_expr.meta_is_column() is False


def test_col_and_arithmetic_expressions():
    # 2. PyExpr column construction and meta inspection
    col_expr = pr.col("price")
    assert col_expr.meta_is_column() is True
    assert col_expr.meta_root_names() == ["price"]
    assert col_expr.meta_output_name() == "price"

    # 3. Arithmetic operations and aliasing
    aliased = (col_expr * pr.lit(1.1, False, True)).alias("total_price")
    assert aliased.meta_is_column() is False
    assert aliased.meta_root_names() == ["price"]
    assert aliased.meta_output_name() == "total_price"

    # 4. meta_undo_aliases reverts to original column name
    unaliased = aliased.meta_undo_aliases()
    assert unaliased.meta_output_name() == "price"


def test_meta_predicate_aliasing_flags():
    col_expr = pr.col("price")
    pure_alias = col_expr.alias("p")
    assert pure_alias.meta_is_column_selection(False) is False
    assert pure_alias.meta_is_column_selection(True) is True

    lit_expr = pr.lit(100, False, True)
    aliased_lit = lit_expr.alias("constant_val")
    assert aliased_lit.meta_is_literal(False) is False
    assert aliased_lit.meta_is_literal(True) is True


def test_when_then_otherwise_conditionals():
    # 5. Conditional branching expressions
    cond = (
        pr.when(pr.col("score") >= pr.lit(50, False, True))
        .then(pr.lit("pass", False, True))
        .otherwise(pr.lit("fail", False, True))
    )
    assert cond.meta_root_names() == ["score"]


def test_stream_serialization_and_equality():
    col_expr = pr.col("price")
    expr = (col_expr * pr.lit(1.1, False, True)).alias("total_price")

    # 6. serialize_json requires a writable stream buffer
    try:
        expr.serialize_json()
        raise AssertionError("serialize_json() should require a stream buffer")
    except TypeError as exc:
        assert "missing 1 required positional argument: 'py_f'" in str(exc)

    json_buf = io.BytesIO()
    expr.serialize_json(json_buf)
    json_buf.seek(0)
    deserialized_json = pr.PyExpr.deserialize_json(json_buf)
    assert expr.meta_eq(deserialized_json) is True

    # 7. serialize_binary into buffer and deserialize
    bin_buf = io.BytesIO()
    expr.serialize_binary(bin_buf)
    bin_buf.seek(0)
    deserialized_bin = pr.PyExpr.deserialize_binary(bin_buf)
    assert expr.meta_eq(deserialized_bin) is True


if __name__ == "__main__":
    test_lit_argument_shape()
    test_col_and_arithmetic_expressions()
    test_meta_predicate_aliasing_flags()
    test_when_then_otherwise_conditionals()
    test_stream_serialization_and_equality()

Исходный сидер

аноним