2023-08-04 16:39:20 +02:00
This rule raises an issue when a dictionary unpacking operation is performed on an invalid mapping object.
2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-08-04 16:39:20 +02:00
Dictionary unpacking allows you to pass the key-value pairs of a dictionary as keyword arguments to a function or merge dictionaries:
[source,python]
----
def foo(a, b):
print(a+b)
my_dict = {"a": 1, "b": 2}
foo(**my_dict) # will print 3
----
2022-09-26 10:41:16 +02:00
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
2023-08-04 16:39:20 +02:00
=== Code examples
2021-04-28 18:08:03 +02:00
2023-08-04 16:39:20 +02:00
==== Noncompliant code example
2021-04-28 16:49:39 +02:00
2023-08-04 16:39:20 +02:00
[source,python,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
class A:
pass
2024-08-26 16:00:15 +02:00
{'a': 10, 'b': 20, **A()} # Noncompliant
2021-04-28 16:49:39 +02:00
----
2021-04-28 18:08:03 +02:00
2023-08-04 16:39:20 +02:00
==== Compliant solution
2021-04-28 16:49:39 +02:00
2023-08-04 16:39:20 +02:00
[source,python,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
class A:
def __getitem__(self, key):
return 2
def keys(self):
return ['1','2','3']
{'a': 10, 'b': 20, **A()} # => {'a': 10, 'b': 20, '1': 2, '2': 2, '3': 2}
----
2021-04-28 18:08:03 +02:00
2023-08-04 16:39:20 +02:00
== Resources
=== Documentation
* Python Documentation - https://docs.python.org/3/glossary.html#term-mapping[mapping]
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
X is of type Y and cannot be unpacked with "**". Use a "mapping" object instead.
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]