[issue32854] Add ** Map Unpacking Support for namedtuple

John Crawford report at bugs.python.org
Thu Feb 15 13:10:32 EST 2018


New submission from John Crawford <jtcrwfrd at gmail.com>:

At present, `collections.namedtuple` does not support `**` map unpacking despite being a mapping style data structure.  For example:

    >>> from collections import namedtuple
    >>> A = namedtuple("A", "a b c")
    >>> a = A(10, 20, 30)
    >>> def t(*args, **kwargs):
    ...     print(f'args={args!r}, kwargs={kwargs!r}')
    ...
    >>> t(*a)
    args=(10, 20, 30), kwargs={}
    >>> t(**a)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: t() argument after ** must be a mapping, not A
    >>> 

No doubt, the lack of current support is due to namespace conflicts that result from trying to provide a `keys` method amidst also supporting attribute-style access to the `namedtuple` class.  As we can see, providing a `keys` attribute in the `namedtuple` produces an interesting result:

    >>> Record = namedtuple("Record", "title keys description")
    >>> t(**Record(1, 2, 3))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: attribute of type 'int' is not callable
    >>>

To me, this calls out a design flaw in the `**` unpacking operator where it depends on a method that uses a non-system naming convention.  It would make far more sense for the `**` operator to utilize a `__keys__` method rather than the current `keys` method.  After all, the `__<methodname>__` naming convention was introduced to avoid namespace conflict problems like this one.

----------
components: Library (Lib)
messages: 312218
nosy: John Crawford
priority: normal
severity: normal
status: open
title: Add ** Map Unpacking Support for namedtuple
type: enhancement
versions: Python 3.7, Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32854>
_______________________________________


More information about the Python-bugs-list mailing list