Skip to content

Support dict subclasses in PyCall::Dict#each and #has_key? - #237

Merged
mrkn merged 3 commits into
red-data-tools:masterfrom
felixmarch:claude/fix-issue-131-dict-subclass-1d3eba
Nov 14, 2026
Merged

mrkn merged 3 commits into
red-data-tools:masterfrom
felixmarch:claude/fix-issue-131-dict-subclass-1d3eba

Conversation

@felixmarch

Copy link
Copy Markdown
Contributor

Fixes #131.

Problem

Instances of dict subclasses, such as pandas' PrettyDict returned by DataFrame.groupby(...).groups, collections.OrderedDict, defaultdict, and Counter, are wrapped as PyCall::Dict, because the Python type mapping falls back to the nearest mapped ancestor. However, LibPython::Helpers.dict_each and dict_contains required the exact dict type, so #each, #to_h, and #has_key? (and its aliases) raised:

TypeError: unexpected Python type PrettyDict (expected dict)

#length, #[], #[]=, and #delete already worked because they use the generic object protocol.

Change

  • dict_each and dict_contains now accept an instance of dict or any subclass of it.
  • An exact dict keeps the existing PyDict_Next / PyDict_Contains fast paths.
  • A subclass is iterated through its items() and checked with in (PySequence_Contains), as Python code would do. The C dict API bypasses Python-level overrides of items() and __contains__, and for OrderedDict it ignores the dict's own ordering (for example after move_to_end), so going through items() keeps the Ruby view consistent with Python's.
  • If a subclass's items() yields something other than 2-tuples, TypeError is raised.

Tests

New specs in spec/pycall/dict_spec.rb, with a small helper module spec/python/pycall/dict_subclass.py (no pandas dependency):

  • #each / #to_h on an exact dict
  • a subclass that overrides nothing (like PrettyDict)
  • OrderedDict iteration order after move_to_end
  • defaultdict (#has_key? does not insert a missing key)
  • Counter
  • a subclass overriding items, __iter__, and __contains__
  • a subclass whose items() does not return pairs
  • break out of #each

The reporter's example now works with the pandas gem (pandas 3.x):

"a"
RangeIndex(start=0, stop=2, step=1)
"b"
RangeIndex(start=2, stop=3, step=1)

🤖 Generated with Claude Code

@mrkn

mrkn commented Nov 13, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T02:36:16.614886Z e35d831 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e35d831373

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mrkn mrkn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I confirmed a reference leak in the dict subclass iteration path; details are in the inline comment.

Comment thread ext/pycall/pycall.c Resolved

@mrkn mrkn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One additional suggestion on matching Python's item-unpacking behavior.

Comment thread ext/pycall/pycall.c Resolved

@mrkn mrkn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested regression coverage for the key reference held during a failed value conversion.

Comment thread spec/pycall/dict_spec.rb Resolved
felixmarch and others added 3 commits November 14, 2026 23:37
…tools#131)

Instances of dict subclasses (pandas' PrettyDict, OrderedDict,
defaultdict, Counter, ...) are wrapped as PyCall::Dict because the type
mapping falls back to the nearest mapped ancestor, but the dict_each and
dict_contains helpers required the exact dict type, so #each, #to_h and
#has_key? raised "unexpected Python type PrettyDict (expected dict)".

Accept any dict subclass. Exact dicts keep the PyDict_Next and
PyDict_Contains fast paths. Subclasses are iterated through items() and
checked with `in`, as Python code would, so overridden items() or
__contains__ and OrderedDict's own order (e.g. after move_to_end) are
honored instead of being bypassed by the C dict API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Address review feedback on the dict subclass iteration path:

- Keep the current item, its key and value, and any per-item iterator
  in state released by the rb_ensure handler.  Previously, if converting
  the key or value raised a Ruby exception (e.g. from a registered type
  mapping's wrap_pyptr), the item and its elements were never decref'd.

- Unpack each item the way Python's `for k, v in obj.items()` does:
  an exact tuple or list is unpacked directly, and any other iterable,
  including tuple and list subclasses, must yield exactly two elements
  through iteration.  Failures raise PyCall::PyError with Python's own
  ValueError / TypeError messages instead of a Ruby TypeError that only
  accepted 2-tuples.

Add PyExc_ValueError to the API table for these errors, and add specs
for list, iterator, and tuple-subclass pairs, too few / too many
elements, non-iterable items, and reference counts when key or value
conversion fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mrkn
mrkn force-pushed the claude/fix-issue-131-dict-subclass-1d3eba branch from f1cf319 to 4755c02 Compare November 14, 2026 14:37
@mrkn
mrkn merged commit 267b450 into red-data-tools:master Nov 14, 2026
42 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can't iterate PrettyDict of Pandas

2 participants