New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MappingProxyType accepts string #87994
Comments
MappingProxyType objects can currently be initialized from a string object. Given is purpose, I think this is a bug and should result in TypeError being raised. Example code (on CPython 3.9.1): >>> from types import MappingProxyType
>>> mp = MappingProxyType('abc')
>>> list(mp)
['a', 'b', 'c']
>>> mp.items()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'items' Other invalid input types are properly checked: >>> mp = MappingProxyType(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mappingproxy() argument must be a mapping, not int
>>> mp = MappingProxyType(['a'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mappingproxy() argument must be a mapping, not list
>>> mp = MappingProxyType(('a',))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mappingproxy() argument must be a mapping, not tuple |
This isn't a bug because the MappingProxy doesn't promise to do early detection and because it can't really be accomplished cleanly. Perfect detection of non-mappings isn't possible. Some easy, minimal checks are made for early detection using PyMapping_Check, PyList_Check, and PyTuple_Check. Anything that gets past those checks will just need to be duck-typed downstream when it is used. We could add a few other specific exclusions but that isn't a general solution and it slows down instantiation. Further it could break code that is intended to work (subclasses of str that mapping methods) or that just happen to work: >>> from types import MappingProxyType
>>> mp = MappingProxyType('abc')
>>> mp[0]
'a' |
I accept that the issue was closed, but wanted to document some things:
>>> d = dict('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> mp = MappingProxyType('abc')
>>> mp.items()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'items' |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: