В линтерах во многих языках программирования есть такая проверка: https://docs.astral.sh/ruff/rules/too-many-return-statements/
По ссылке приведён тривиальный пример, где достаточно сопоставления по ключу.
В общем случае код выглядит примерно как:
def f(x):
if cond1(x):
return res1
y = process1(x);
if cond2(y):
return res2
if cond3(y):
return res3
z = process2(x, y)
if cond4(x,y,z):
return res4
if cond5(x,y,z):
return res5
...
после убирания return получается что-то вроде
def f(x):
done = False
if cond1(x):
res = res1
done = True
if not done:
y = process1(x);
if not done and cond2(y):
res = res2
done = True
if not done and cond3(y):
res = res3
done = True
if not done:
z = process2(x, y)
if not done and cond4(x,y,z):
res = res4
done = True
if not done and cond5(x,y,z):
res = res5
done = True
...
return res
Второй вариант действительно легче читается или я неправильно преобразовал первый во второй?
UPD: С учётом наличия elif
def f(x):
done = False
if cond1(x):
res = res1
done = True
if not done:
y = process1(x);
if cond2(y):
res = res2
done = True
elif cond3(y):
res = res3
done = True
if not done:
z = process2(x, y)
if cond4(x,y,z):
res = res4
done = True
elif cond5(x,y,z):
res = res5
done = True
...
return res
Вот это читается легче, чем первый вариант?









