CodeSampleX

Пример

pandas 2.3.3: Chained assignment discards mutations while text columns default to object dtype and fallback to python storage without pyarrow

Проверенный пример — pypi pandas 2.3.3: Chained assignment discards mutations while text columns default to object dtype and fallback to python storage…

sha256:5b203a9e6192c6686bbbd1529e7f7bb5434622bb6f964dc64a9b4f53cc9f5c4e

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
3
Ключи подписи, собравшие его
3
Заявленная среда python linux x64 python python pip

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

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

Кейс

HOW
Цель
Chained assignment discards mutations while text columns default to object dtype and fallback to python storage without pyarrow
Пакеты
Символы
  • pandas.DataFrame
  • pandas.Series
  • pandas.StringDtype
  • pandas.errors.ChainedAssignmentError
  • pandas.errors.SettingWithCopyWarning
  • pandas.options.mode.copy_on_write
Окружение
python
Создан
2026-08-15T02:48:25Z

Контракт

  1. assert df[df['a'] > 1]['b'] = 99 warns SettingWithCopyWarning and leaves df['b'] unmodified
  2. assert under copy_on_write df['b'][0] = 99 warns ChainedAssignmentError and leaves df.loc[0, 'b'] unmodified
  3. assert df['text'].dtype == object and df['text'].dtype != 'string'
  4. assert pd.Series(['a'], dtype='string').dtype.storage == 'python'
  5. assert pd.Series(['a'], dtype='string[pyarrow]') raises ImportError when pyarrow is absent
  6. assert pd.Series(['a', None], dtype='string').iloc[1] is pd.NA

Файлы

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

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

Исходный код

NOTES.md
A model would write `df[df['col'] > 0]['target'] = 1` or `df['target'][0] = 1` to modify tabular data in-place, inspect text columns with `df['text'].dtype == 'string'`, and assume `dtype='string'` uses PyArrow backend with `np.nan` nulls.
The wrong code fails silently with a green build: chained assignments execute without updating the original DataFrame, `df.select_dtypes(include='string')` silently drops text columns, and null checks against `np.nan` or `None` evaluate false against `pd.NA`.
csx.json
{"case":{"caseId":"case:sha256:bbb13106a78f5abd7d3ec0a1c8a3e5a76e79558e89f95f30c2374f404209601d","constraints":{"runtime":"python"},"contract":["assert df[df['a'] \u003e 1]['b'] = 99 warns SettingWithCopyWarning and leaves df['b'] unmodified","assert under copy_on_write df['b'][0] = 99 warns ChainedAssignmentError and leaves df.loc[0, 'b'] unmodified","assert df['text'].dtype == object and df['text'].dtype != 'string'","assert pd.Series(['a'], dtype='string').dtype.storage == 'python'","assert pd.Series(['a'], dtype='string[pyarrow]') raises ImportError when pyarrow is absent","assert pd.Series(['a', None], dtype='string').iloc[1] is pd.NA"],"goal":"Chained assignment discards mutations while text columns default to object dtype and fallback to python storage without pyarrow","kind":"HOW","packages":["pkg:pypi/pandas@2.3.3"],"schemaVersion":1,"symbols":["pandas.DataFrame","pandas.Series","pandas.StringDtype","pandas.errors.ChainedAssignmentError","pandas.errors.SettingWithCopyWarning","pandas.options.mode.copy_on_write"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pandas@2.3.3"],"schemaVersion":1,"symbols":["pandas.DataFrame","pandas.Series","pandas.StringDtype","pandas.errors.ChainedAssignmentError","pandas.errors.SettingWithCopyWarning","pandas.options.mode.copy_on_write"],"verifierAdapter":"python@1"}
requirements.lock
numpy==2.2.6
pandas==2.3.3
python-dateutil==2.9.0.post0
pytz==2026.1.post1
six==1.17.0
tzdata==2026.1
requirements.txt
numpy==2.2.6
pandas==2.3.3
python-dateutil==2.9.0.post0
pytz==2026.1.post1
six==1.17.0
tzdata==2026.1
test/contract.py
import warnings
import numpy as np
import pandas as pd


def test_chained_assignment():
    df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        df[df["a"] > 1]["b"] = 99
        assert any(issubclass(item.category, pd.errors.SettingWithCopyWarning) for item in w)
    assert df["b"].tolist() == [10, 20, 30]

    with pd.option_context("mode.copy_on_write", True):
        df_cow = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
        with warnings.catch_warnings(record=True) as w_cow:
            warnings.simplefilter("always")
            df_cow["b"][0] = 99
            assert any(issubclass(item.category, pd.errors.ChainedAssignmentError) for item in w_cow)
        assert df_cow.loc[0, "b"] == 10

        sub = df_cow[df_cow["a"] > 1]
        with warnings.catch_warnings(record=True) as w_sub:
            warnings.simplefilter("always")
            sub.loc[:, "b"] = 999
            assert len(w_sub) == 0
        assert sub["b"].tolist() == [999, 999]
        assert df_cow["b"].tolist() == [10, 20, 30]


def test_text_column_dtypes():
    df = pd.DataFrame({"text": ["apple", "banana"]})
    assert df["text"].dtype == object
    assert df["text"].dtype != "string"
    assert df["text"].dtype != str
    assert not isinstance(df["text"].dtype, pd.StringDtype)
    assert df.select_dtypes(include="string").empty
    assert df.select_dtypes(include=object).shape == (2, 1)

    s_str = pd.Series(["apple", None], dtype="string")
    assert isinstance(s_str.dtype, pd.StringDtype)
    assert s_str.dtype.storage == "python"
    assert s_str.iloc[1] is pd.NA
    assert s_str.iloc[1] is not np.nan
    assert s_str.iloc[1] is not None
    assert (s_str.iloc[1] == pd.NA) is pd.NA

    try:
        pd.Series(["apple"], dtype="string[pyarrow]")
        has_pa = True
    except ImportError:
        has_pa = False
    assert not has_pa


if __name__ == "__main__":
    test_chained_assignment()
    test_text_column_dtypes()
    print("Contract tests passed successfully.")

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

anonymous