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:
- add overhead by creating an intermediate collections
- add verbosity without providing any additional functionality
- add ambiguity and may mislead readers or imply a more complex operation than what is actually occurring
Exceptions
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 S7500 - Comprehensions only used to copy should be replaced with the respective constructor calls,
will raise an issue.