elements-of-python-style
elements-of-python-style copied to clipboard
Assignments/function calls in a return statement?
Probably a personal preference, but I like to have values already set or calculated before the return is called. This example from Django, as part of a typical views module:
def some_view(request):
"""Some description."""
# ... some processing
context = dict(
admin.site.each_context(request),
query='hard_coded',
query_fields=some_fn('param'))
return render(
request=request,
template_name='query/query.html',
context=context)
The context can contain many variables, and I think its easier for readability and debugging purposes to create/set all of its values before the return is called; it is an extra variable but I find the trade-off is worth it.
I found another example that I wrote for our internal team guidelines:
Do not create values for a function parameter as part of the call to that function. This makes debugging and testing really difficult. For example, instead of:
do_something(x=1, y=a*2 + 23 - z**3)
rather:
y = a*2 + 23 - z**3
logger.debug('y=%s', y)
do_something(x=1, y=y)
This is an interesting suggestion, thank you @gamesbook!
I personally tend to follow your style (of setting a label for a complex calculation before issuing a yield or return). My reasoning usually comes down to "self-documentation", that is, naming the result of that "step" of calculation, even if it is the final step before return. A side benefit is that it makes code easier to debug (with a breakpoint debugger). But, I wonder whether one could make a "rule" out of this, as clearly simple return and yield statements (e.g. return True and even return sum(some_sequence)) feel like they are better left alone. This puts it on the edge of being a style suggestion vs being in my "Six of One, Half a Dozen of the Other" section.
Labeling this "research needed" for now.