Inline Immediately Returned Variables
Sourcery refactoring id: inline-immediately-returned-variable
Description
Inlines a variable to a return
in the case when the variable being declared is
immediately returned
Before
def state_attributes(self):
"""Return the state attributes."""
state_attr = {
ATTR_CODE_FORMAT: self.code_format,
ATTR_CHANGED_BY: self.changed_by,
}
return state_attr
After
def state_attributes(self):
"""Return the state attributes."""
return {
ATTR_CODE_FORMAT: self.code_format,
ATTR_CHANGED_BY: self.changed_by,
}
Explanation
Something that we often see in people's code is assigning to a result variable and then immediately returning it.
Returning the result directly shortens the code and removes an unnecessary variable, reducing the mental load of reading the function.
Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is - in the example above
it's the state attributes, and the state_attr
name wasn't providing any extra
information.