Python: if Condition, then skip to return

I was wondering if there is a good way to tell the python interpreter to go to the next / last function return statement .

Let's assume the following dummy code:

def foo(bar):
  do(stuff)

  if condition:
    do(stuff)
    if condition2:
      do(stuff)
      if condition3:
        ...

  return (...)

Sometimes it gets very dirty with many conditions that I cannot use because they rely on the block do(stuff)above. Now I can do this:

def foo(bar):
  do(stuff)

  if not condition: return (...)
  do(stuff)
  if not condition2: return (...)
  do(stuff)
  if not condition3: return (...)
    ...

  return (...)

It looks a little less dirty, but I will have to repeat the returned statement again and again, which is a bit reminiscent of, and if its long tuple or similar it even looks worse. The ideal solution would be to say "if not a condition, skip the final return statement". Is it possible?

:, : - ,

+4
2

, ( , do(stuff) - ). for:

list_of_funcs = [func1, func2, func3]
for func in list_of_funcs:
    func(stuff)
    if not condition:
        break
return (...)

, ( , True False), zip :

list_of_funcs = [func1, func2, func3]
list_of_conditions = [cond1, cond2, cond3]
for func, cond in zip(list_of_funcs, list_of_conditions):
    func(stuff)
    if not cond():
        break
return (...)

, , , .

+5

- , , , .

class GotoEnd(Exception):
    pass

def foo(bar):

  try:
    do(stuff)
    if not condition: raise GotoEnd
    do(stuff)
    if not condition2: raise GotoEnd

    do(stuff)
    if not condition3: raise GotoEnd

    ...
  except GotoEnd:
    pass

  return (...)
0

Source: https://habr.com/ru/post/1656942/


All Articles