benjaminp / six

Python 2 and 3 compatibility library
https://six.readthedocs.io/
MIT License
987 stars 274 forks source link

Fix the `UserDict` move on Python2 #364

Closed bxsx closed 2 years ago

bxsx commented 2 years ago

Background

The current implementation of the UserDict attribute maps UserDict.UserDict to collections.UserDict:

MovedAttribute("UserDict", "UserDict", "collections"),

From the Python 2.7 documentation:

For backward compatibility, instances of UserDict are not iterable.

This limitation does not exist in Python3. As a result, six introduces a bug in Python2.

Reproduction steps:

from six.moves import UserDict

d = UserDict({'key': 'output'})
for k in d:
    print(d[k])

PY3 output:

output

PY2 output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/bxsx/.pyenv/versions/2.7.18/lib/python2.7/UserDict.py", line 40, in __getitem__
    raise KeyError(key)
KeyError: 0

Solution

This PR addresses it by updating the UserDict attribute to mapUserDict.IterableUserDict on Python 2 and collections.UserDict on Python3. The PR also adds the moved attribute IterableUserDict which maps to the same attributes as UserDict.

The PR fixes #281 issue