2024-08-26 16:00:15 +02:00

62 lines
1.5 KiB
Plaintext

This rule raises an issue when a dictionary unpacking operation is performed on an invalid mapping object.
== Why is this an issue?
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
----
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++``.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
class A:
pass
{'a': 10, 'b': 20, **A()} # Noncompliant
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
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}
----
== Resources
=== Documentation
* Python Documentation - https://docs.python.org/3/glossary.html#term-mapping[mapping]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
X is of type Y and cannot be unpacked with "**". Use a "mapping" object instead.
endif::env-github,rspecator-view[]