[docs] [issue24659] dict() built-in fails on iterators with a "keys" attribute

Raymond Hettinger report at bugs.python.org
Sun Jul 19 02:23:42 CEST 2015


Raymond Hettinger added the comment:

> I'm aware of duck typing but I don't think this 
> is the right place for it. 

The code for dicts is very old, stable, and unlikely to change.  Also, the logic of checking for .keys() is immortalized in the collections.abc.MutableMapping update() method.

For the most part, consumers of iterables, sequences, and mappings are allowed to use duct-typing (this is a feature of the language, not a bug).

The docs can be improved in a number of places.  For example the docstring on the dict constructor is out of sync with the dict.update() method:

    >>> print(dict.__doc__)
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    >>> print(dict.update.__doc__)
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
    If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
    In either case, this is followed by: for k in F:  D[k] = F[k]

In addition, the glossary entries for iterable, sequence, and mapping need to be improved to distinguish between their somewhat vague use in a general sense versus the specific meaning of isinstance(obj, Mapping).  Unless the docs specify a check for the latter, they almost always do some form of duck-typing or a check for concrete built-in class or subclass.

Terms like "mapping" and "sequence" are often used somewhat generally both inside and outside the Python world.  Sometimes mapping is used in the mathematic sense (pairing each member of the domain with each member of the range), http://www.icoachmath.com/math_dictionary/mapping.html, and sometimes in the sense of a subset of dict capabilities (i.e. has __getitem__ and keys).  

The docs for PyMapping_Check() need to be updated to indicate the known limitations of the check and to disambiguate it from isinstance(obj, Mapping).

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24659>
_______________________________________


More information about the docs mailing list