29 lines
723 B
Plaintext
29 lines
723 B
Plaintext
Dictionary unpacking requires an objects with methods ``++__getitem__++`` and ``++keys++`` or ``++__getitem__++`` and ``++__getattr__++``. This is the case for any https://docs.python.org/3/glossary.html#term-mapping[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}
|
|
----
|
|
|