Xuan Linh Ha
Xuan Linh Ha

Reputation: 33

How to exit some intermediate functions in Python

def check():
    if (cond):
        how to return back to explore()
    else:
        return 1 # here return to f2

def cannot_be_modified():
    try:
        check() # inserted
        print("hello from cannot_be_modified")
        return 2
    except Exception as e:
        print(e)

def explore():
    cannot_be_modified()
    print("hello from explore")
    return 0

explore()

Call stack is: explore() -> cannot_be_modified() --> check()

If I meet some conditions in check, I want to quit check and cannot_be_modified and come back to explore. So how can I achieve this?

I thought about raising a specific type of exception in check function and catch it in explore but that exception can be caught in function cannot_be_modified

Does anyone have ideas?

Thanks

Upvotes: 1

Views: 50

Answers (1)

Gsk
Gsk

Reputation: 2945

Even if it's not the most elegant solution, you may decide to raise an exception (built-in or custom) in your check function and catch that in the explorer function. Be sure that you're catching only your exception.

def check():
  if True:
      raise ValueError("MyError")
  else:
      return 1 # here return to f2

def cannot_be_modified():
    check() # inserted
    print("hello from cannot_be_modified")
    return 2

def explore():
  try:
    cannot_be_modified()
  except ValueError as e:
    print(e)

  print("hello from explore")
  return 0

explore()

output:

MyError
hello from explore

Upvotes: 1

Related Questions