Dictionary unpacking requires an object with methods __getitem__
and keys
or __getitem__
and
__getattr__
. This is the case for any mapping object such as
dict
. Using an object which doesn’t have these methods will raise a TypeError
.
Noncompliant Code Example
class A:
pass
dict(**A()) # Noncompliant
{'a': 10, 'b': 20, **A()} # Noncompliant
Compliant Solution
class A:
def __getitem__(self, key):
return 2
def keys(self):
return ['1','2','3']
dict(**A()) # => {'1': 2, '2': 2, '3': 2}
{'a': 10, 'b': 20, **A()} # => {'a': 10, 'b': 20, '1': 2, '2': 2, '3': 2}