rspec/rules/S6465/python/rule.adoc
2023-08-04 13:21:13 +02:00

34 lines
1.1 KiB
Plaintext

This rule raises an issue when the number of variables on the left-hand side of an assignment operator (=) doesn't match the number of elements in the iterable on the right-hand side.
== Why is this an issue?
In Python, the unpacking assignment is a powerful feature that allows you to assign multiple values to multiple variables in a single statement.
The basic rule for the unpacking assignment is that the number of variables on the left-hand side must be equal to the number of elements in the iterable. If this is not respected, a ``++ValueError++`` will be produced at runtime.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
def foo(param):
ls = [1, 2, 3]
x, y = ls # Noncompliant: 'ls' contains more elements than there are variables on the left-hand side
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
def foo(param):
ls = [1, 2, 3]
x, y, z = ls
----
== Resources
=== Documentation
* Python Documentation - https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences[Tuples and Sequences]