Identity Comprehensions
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: identity-comprehension
Section titled “Sourcery refactoring id: identity-comprehension”Description
Section titled “Description”Convert list/set/tuple comprehensions that do not change the input elements into
Before
Section titled “Before”# List comprehensions[item for item in coll][item for item in friends.names()]
# Dict comprehensions{k: v for k, v in coll}{k: v for k, v in coll.items()} # Only if we know coll is a `dict`
# Unneeded call to `.items()`dict(coll.items()) # Only if we know coll is a `dict`
# Set comprehensions{item for item in coll}# List comprehensionslist(iter(coll))list(iter(friends.names()))
# Dict comprehensionsdict(coll)dict(coll)
# Unneeded call to `.items()`dict(coll)
# Set comprehensionsset(coll)Explanation
Section titled “Explanation”All these comprehensions are just creating a copy of the original collection. They can all be simplified by simply constructing a new collection directly. The resulting code is easier to read and shows the intent more clearly.