This rule raises an issue when calls to tuple(), list(), set(), or dict() are done with an
argument that is either already a collection literal or a comprehension.
Python provides direct ways to create common data structures like tuples, lists, and dictionaries using literals, e.g., (),
(1,2), [], [1,2], {}, {'a':1} and comprehensions e.g., [x for x in y],
{k:v for k,v in y}. Wrapping these direct forms in a type constructors is unnecessary, as shown in the following examples:
tuple((1,2))
list([1,2])
list([x for x in [1,2]])
set({})
set({for k in [1,2]})
dict({'a':1})
dict({k:v for k,v in [1,2]})
dict([(1,"a"), (2, "b")])
Such constructs:
If there are no modification in the comprehension such as list([x for x in [1,2]]) which is the same as [1,2], this rule
will not raise an issue; instead rule {rule:python:S7500} - Comprehensions only used to copy should be replaced with the respective constructor calls,
will raise an issue.
To fix this, remove the constructor call and use the literal or comprehension syntax of the target type. As an exception, for a list or
comprehension inside of a tuple constructor replace the comprehension by a generator.
t1 = tuple([1, 2]) # Noncompliant: the tuple creation can be done directly without the intermediate list
t1 = (1, 2) # Compliant
l1 = list([x * 2 for x in [1,2,3]]) # Noncompliant: list is redundant.
l1 = [x * 2 for x in [1,2,3]] # Compliant
s1 = set([x * 2 for x in [1,2,3]]) # Noncompliant: the set creation can be done with a set comprehension.
s1 = {x * 2 for x in [1,2,3]} # Compliant