Some functions return values: return value, some have only early returns if ...: return
Some return None as a value, some just can have it as the last statement.
This is wrong:
def test():
print('test')
return
def test():
print('test')
return None
def test(some):
if some:
return
print('test')
return
These are correct:
def test():
print('test')
def test(some):
if some:
return
print('test')
def test(some):
if some:
return some
print('test')
return None
The rule is related to #378
The rule is:
return is the last statementreturn, then raise a violationreturn None check if that is the only return in the function, if so raise a violationThis is done for consistency. It should also improve the readability and typing.
Hey @sobolevn! Can I pick this up?
Sure, feel free to ask me any questions. Thanks for your help!
Hey @sobolevn! Can you guide me where I could start for this?
@NanduTej sure!
There are several things to start with:
AnyFunction nodes (which are AsyncFunctionDef + FunctionDef)body (we can iterate for all nodes in node.body and get the last one by lineno)Please, ask any questions you have or send Work-in-Progress Pull Requests so I can guide you.
I would say that ConsistentReturningVariableVisitor is the best class to use
Should this function be added in visitors/ast/exceptions.py?
visitor/ast/keywords.py::ConsistentReturningVariableVisitor
Earlier, tests for these cases seem to have been written here. https://github.com/wemake-services/wemake-python-styleguide/blob/49e232d785a12259fcf8ed0e6b69fc625a166b23/tests/test_visitors/test_ast/test_keywords/test_consistency_returning/test_consistency_return.py#L14. Should these tests be removed from there and added to test_consistent_returning_variable.py? I am not yet done with my work. I just understood the flow but found these while looking around.
Yes, they should be changed. I wrote them because it was fine before this rule.
Hey! I was trying to reproduce some of the tests code in my terminal. I could not figure out where we are getting default_options https://github.com/wemake-services/wemake-python-styleguide/blob/49e232d785a12259fcf8ed0e6b69fc625a166b23/tests/test_visitors/test_ast/test_keywords/test_consistency_returning/test_consistency_return_variables.py#L140 from. Can you help me out?
We are using pytest's fixtures to do that.
Docs: https://docs.pytest.org/en/latest/fixture.html
Code: https://github.com/wemake-services/wemake-python-styleguide/blob/master/tests/conftest.py#L77-L98
Hey, @NanduTej, thanks for your help! Check out the final solution.