Skip to content

[Bug]: collections._count_elements looks up mapping.get before calling iter() on the iterable #1250

Open

Description

@jseop-lim

Describe the bug

_collections has no _count_elements, so collections._count_elements is the pure-Python fallback in collections/__init__.py. That fallback reads mapping.get before it iterates, while CPython's C helper gets the iterator first. When both arguments are bad, GraalPy raises the mapping's AttributeError and CPython raises the iterable's error.

Operating system

macOS

CPU architecture

ARM64

GraalPy version

master a3009f9 (Python 3.13.14); also reproduced on 25.0.2 (Python 3.12.8)

JDK version

No response

Context configuration

No response

Steps to reproduce

import collections

class NoneIter:
    def __iter__(self):
        return None

collections._count_elements(None, NoneIter())

GraalPy master a3009f9:

AttributeError: 'NoneType' object has no attribute 'get'

Expected behavior

CPython 3.13.14 (same on 3.12.13):

TypeError: iter() returned non-iterator of type 'NoneType'

Stack trace

Additional context

CPython's own pure-Python fallback behaves the same way when _collections is blocked, and Counter.update() always passes a mapping that has get, so only direct callers of the private helper see the difference. GraalPy already patches torch._dynamo to substitute collections._count_elements because _collections._count_elements is missing (torch-2.10.0.patch#L540-L553).

Root Cause

collections/__init__.py#L537-L546 evaluates mapping.get and only then iterates, and from _collections import _count_elements fails because CollectionsModuleBuiltins (CollectionsModuleBuiltins.java#L51-L52) does not define it. CPython's _collections__count_elements_impl calls PyObject_GetIter(iterable) first (_collectionsmodule.c#L2514-L2516) and looks up get afterwards (#L2575).

Fix Suggestion

Provide _count_elements in _collections that gets the iterator before looking up mapping.get.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions