Skip to content

python-stdlib/collections-defaultdict: Add items() function.#1100

Open
agatti wants to merge 1 commit intomicropython:masterfrom
agatti:collections-defaultdict-items
Open

python-stdlib/collections-defaultdict: Add items() function.#1100
agatti wants to merge 1 commit intomicropython:masterfrom
agatti:collections-defaultdict-items

Conversation

@agatti
Copy link
Contributor

@agatti agatti commented Mar 23, 2026

Summary

This PR adds the items() functions to collections.defaultdict, acting as a simple proxy to the underlying dictionary container.

This fixes #350.

The package's version number was bumped up by 0.1.0 since a new function was added to the module.

Testing

The added tests in python-stdlib/collections-defaultdict were run successfully both on CPython (with a tweaked import harness) and on MicroPython's git master.

Trade-offs and Alternatives

This adds 81 bytes to the final module. I'm a bit surprised it took that much, but unless it is documented that the backing dictionary can be accessed via self.d when code runs on MicroPython, I don't see any other safe way to enumerate the contents [1].

Generative AI

I did not use generative AI tools when creating this PR.


[1]

This trips up MicroPython, for example:

from collections import defaultdict
a = defaultdict.defaultdict(list)
for i in a:
    print(i)

On current MicroPython's git master:

$ cd python-stdlib/collections-defaultdict
$ $MICROPYTHON
MicroPython v1.28.0-preview.306.g5c00edcee2.dirty on 2026-03-23; linux [GCC 15.2.1] version
Type "help()" for more information.
>>> from collections import defaultdict
>>> a = defaultdict.defaultdict(list)
>>> for i in a:
...     print(i)
...
[]
[]
[]
[]
# `[]` being repeated a fairly large number of times here...
[]
[]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "collections/defaultdict.py", line 20, in __getitem__
MemoryError: memory allocation failed, allocating 260368 bytes
>>>

Whilst this works as expected on CPython 3.14 (and probably earlier versions too):

$ python
Python 3.14.3 (main, Feb 13 2026, 15:31:44) [GCC 15.2.1 20260209] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> a = defaultdict(list)
>>> for i in a:
...     print(i)
... 
>>>

This commit adds the `items()` functions to `collections.defaultdict`,
acting as a simple proxy to the underlying dictionary container.

This fixes micropython#350.

Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
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.

AttributeError: 'defaultdict' object has no attribute 'items'

1 participant