42 lines
943 B
Plaintext
42 lines
943 B
Plaintext
== Why is this an issue?
|
|
|
|
Dictionary unpacking requires an object 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
|
|
|
|
[source,python]
|
|
----
|
|
class A:
|
|
pass
|
|
|
|
dict(**A()) # Noncompliant
|
|
{'a': 10, 'b': 20, **A()} # Noncompliant
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,python]
|
|
----
|
|
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}
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|