M
Marco Aschwanden
Hi
I checked the other day a module of mine with pylint. And for some
function it told me, that I was using too many return-statements in my
code... there were about 5 or 7 of them in my function.
Through books I learned, that there should be only 1 return statement in a
function. This makes for clear code - they said. I tried to stick to this
principle for a very long time... ending up with deeper and deeper nested
if-then-else-clauses and hided code-sections with clever if-then-clauses
when the return value was already clear or when the code was not eligible
for this specific return value:
# Example 1: "Good" style according to the books
def func(value):
return_value = xyz
IF not wrong value:
do something does change return_value
IF do soemthing worked out:
do something else...
IF not return_value == xyz:
do something other with return_value
return return_value
Meanwhile I have adopted a style that jumps out of the function when some
condition is reached. I don't have to bother afterwards with this case. In
my eyes, this style produces more readable code:
# Example 2: "Bad" style
def func(value):
return_value = xyz
IF wrong_value:
return wrong_value
do something does change return_value
IF not do soemthing worked out:
return another_wrong_value
do something other with return_value
return return_value
This pylint made me feel guilty again... so I wonder: How do you handle
this? Is "my" style really bad style?
Thanks for your hints in advance,
Greetings,
Marco
I checked the other day a module of mine with pylint. And for some
function it told me, that I was using too many return-statements in my
code... there were about 5 or 7 of them in my function.
Through books I learned, that there should be only 1 return statement in a
function. This makes for clear code - they said. I tried to stick to this
principle for a very long time... ending up with deeper and deeper nested
if-then-else-clauses and hided code-sections with clever if-then-clauses
when the return value was already clear or when the code was not eligible
for this specific return value:
# Example 1: "Good" style according to the books
def func(value):
return_value = xyz
IF not wrong value:
do something does change return_value
IF do soemthing worked out:
do something else...
IF not return_value == xyz:
do something other with return_value
return return_value
Meanwhile I have adopted a style that jumps out of the function when some
condition is reached. I don't have to bother afterwards with this case. In
my eyes, this style produces more readable code:
# Example 2: "Bad" style
def func(value):
return_value = xyz
IF wrong_value:
return wrong_value
do something does change return_value
IF not do soemthing worked out:
return another_wrong_value
do something other with return_value
return return_value
This pylint made me feel guilty again... so I wonder: How do you handle
this? Is "my" style really bad style?
Thanks for your hints in advance,
Greetings,
Marco