Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assignments/function calls in a return statement? #47

Open
gamesbook opened this issue May 15, 2020 · 2 comments
Open

Assignments/function calls in a return statement? #47

gamesbook opened this issue May 15, 2020 · 2 comments
Assignees

Comments

@gamesbook
Copy link

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.

@gamesbook
Copy link
Author

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)

@amontalenti
Copy link
Owner

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.

@amontalenti amontalenti self-assigned this May 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants