Skip to content

Commit 413d646

Browse files
gh-157747: Document that ** unpacking accepts any object with keys()
1 parent 369d8bc commit 413d646

1 file changed

Lines changed: 12 additions & 7 deletions

File tree

‎Doc/reference/expressions.rst‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -629,8 +629,11 @@ For example::
629629

630630
Instead of a key-value pair, a dict item may be an expression prefixed by
631631
a double asterisk ``**``. This denotes :dfn:`dictionary unpacking`.
632-
At runtime, the expression must evaluate to a :term:`mapping`;
633-
each item of the mapping is added to the new dictionary.
632+
At runtime, the expression must evaluate to an object that defines a
633+
``keys()`` method; the new dictionary is created by calling
634+
:meth:`~object.__getitem__` on that object with each key returned by
635+
``keys()``. A :term:`mapping` satisfies this, but any object with those
636+
two methods does.
634637
As with key-value pairs, later values replace values already set by
635638
earlier items and unpackings.
636639
This may be used to override a set of defaults::
@@ -1647,14 +1650,16 @@ used in the same call, so in practice this confusion does not often arise.
16471650
single: **; in function calls
16481651
16491652
If the syntax ``**expression`` appears in the function call, ``expression`` must
1650-
evaluate to a :term:`mapping`, the contents of which are treated as
1651-
additional keyword arguments. If a parameter matching a key has already been
1652-
given a value (by an explicit keyword argument, or from another unpacking),
1653+
evaluate to an object that defines a ``keys()`` method; its contents are
1654+
treated as additional keyword arguments, with each value obtained by
1655+
calling ``__getitem__()`` with each key returned by ``keys()``. If a
1656+
parameter matching a key has already been given a value (by an explicit
1657+
keyword argument, or from another unpacking),
16531658
a :exc:`TypeError` exception is raised.
16541659

1655-
When ``**expression`` is used, each key in this mapping must be
1660+
When ``**expression`` is used, each key returned by ``keys()`` must be
16561661
a string.
1657-
Each value from the mapping is assigned to the first formal parameter
1662+
Each value from the object is assigned to the first formal parameter
16581663
eligible for keyword assignment whose name is equal to the key.
16591664
A key need not be a Python identifier (e.g. ``"max-temp °F"`` is acceptable,
16601665
although it will not match any formal parameter that could be declared).

0 commit comments

Comments
 (0)