rspec/rules/S5633/python/rule.adoc

40 lines
915 B
Plaintext
Raw Normal View History

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++``.
2021-04-28 16:49:39 +02:00
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
class A:
pass
dict(**A()) # Noncompliant
{'a': 10, 'b': 20, **A()} # Noncompliant
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
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[]