python - Use decorators to wrap all functions with "if func returned false, return false" -


i'm writing basic python script based on main function sequentially calls other functions.

what wrap of functions called main like:

result = func(*some_args):    if (result != true):        return result 

for example, code:

def func1(arg1 , arg2):      if (some_cond):         return false #or err_val      return true  def func2(arg1):      if (some_cond):         return false      return true  def main():     func1(val1 , val2)     func2(val3)     return true  if __name__ == "__main__":      import sys      result = main()      if (result == err_val1):           # something. maybe print. maybe call function.           sys.exit(1) 

i want if 1 of functions fails main break , return error. can using decorators?

this precisely exceptions built in python.

# imports belong @ *top* of file import sys   class somedescriptiveerror(exception): pass class someotherspecialerror(exception): pass   def func1(arg1 , arg2):      if (some_cond):         raise somedescriptiveerror('cannot frobnosticate fizzbuzz')      return arg1 + arg2      # or skip return statement altogether  def func2(arg1):      if (some_cond):         raise someotherspecialerror('the frontobulator no longer cromulent')      return ''.join(reversed(arg1))  def main():     print(func1(val1 , val2))     print(func2(val3))  if __name__ == "__main__":      try:          result = main()      except somedescriptiveerror e:          print('oh dear')          sys.exit(e.args[0])      except someotherspecialerror e:          print('oh no')          sys.exit(e.args[0])      else:          print('all systems operational')      finally:          print('i should clean these bits.') 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -