Inline Immediately Returned Variables
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: inline-immediately-returned-variable
Section titled “Sourcery refactoring id: inline-immediately-returned-variable”Description
Section titled “Description”Inlines a variable to a return in the case when the variable being declared is
immediately returned
Before
Section titled “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_attrdef state_attributes(self): """Return the state attributes.""" return { ATTR_CODE_FORMAT: self.code_format, ATTR_CHANGED_BY: self.changed_by, }Explanation
Section titled “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.
One point to note is that if the variable has a type annotation, we will not suggest inlining it, since this would lose that information, possibly leading to type checking errors.