Skip to content

[Fix] Dereference weakrefs when WeakRefList is sliced - #1525

Open
BlueX888 wants to merge 1 commit into
guidance-ai:mainfrom
BlueX888:fix/prep-weakreflist-slice-typeerror
Open

BlueX888 wants to merge 1 commit into
guidance-ai:mainfrom
BlueX888:fix/prep-weakreflist-slice-typeerror

Conversation

@BlueX888

Copy link
Copy Markdown

Summary

Slicing a WeakRefList (e.g. TraceNode.children[0:2]) raised TypeError: 'list' object is not callable. Slicing now returns the referenced objects, consistent with integer indexing.

Why

WeakRefList.__getitem__ (guidance/trace/_trace.py:217-219 on main) unconditionally treated the result of list.__getitem__ as a single weakref and called it. When the index is a slice, list.__getitem__ returns a plain list of weakref objects, and calling a list raises TypeError: 'list' object is not callable. TraceNode.children is a WeakRefList (guidance/trace/_trace.py:247 on main), so any slice access on it crashed.

Changes

  • guidance/trace/_trace.py: WeakRefList.__getitem__ now checks whether the index is a slice. For a slice it dereferences every weakref in the sliced result, raising ReferenceError for dead entries (same behavior as integer indexing) and returning the list of live objects. Integer indexing behavior is unchanged.

Testing

Added regression test test_weak_ref_list_slice and slice assertions in test_trace_node (tests/unit/test_trace.py). On the unpatched tree both fail with TypeError: 'list' object is not callable.

  • python -m pytest tests/unit/test_trace.py — 14 passed
  • python -m pytest tests/unit/ — 1638 passed, 1 skipped, 220 xfailed
  • ruff format --check guidance/trace/_trace.py tests/unit/test_trace.py — 2 files already formatted
  • ruff check --select I,RUF022 guidance/trace/_trace.py tests/unit/test_trace.py — All checks passed

WeakRefList.__getitem__ called the result of list.__getitem__
unconditionally, which is a plain list of weakrefs when the index is
a slice, raising TypeError: 'list' object is not callable. Handle
slice indices by dereferencing each referenced object, so slicing a
TraceNode's children returns TraceNode objects as its list type
annotation implies.

This branch has not been deployed

No deployments
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.

1 participant