0

Can you recommend a nice way of checking a particular value between calls to a set of functions?

E.g. something like this in Python (might not be terribly 'Pythonic'):

self.error_code    = 0 # this will be set by each function if an error has occurred
self.function_list = [self.foo, self.bar, self.qux, self.wobble]
...
def execute_all(self):
    while not self.error_code and self.function_list:
        func = self.function_list.pop() # get each function
        func(error_code) # call it

    if self.error_code:
        # do something

The idea is that subsequent functions won't be called if self.error_code is set and all functions will be called in order if all is good.

Anyone can think of a better alternative to that in Python or maybe a language-agnostic approach?

I want to avoid having that code in each function call (e.g. if self.error code: return) so that I don't end up with the same check across all functions.

  • 3
    This looks like poor man's exception handling. Can't the functions just throw an exception? If you're worried about the same code at the start of all functions, make a decorator that does it. – RemcoGerlich Mar 10 '14 at 12:40
  • @RemcoGerlich Might actually look into decorators (sorry, newb python programmer here). If you want, put it as an answer so I can accept it. – Nobilis Mar 10 '14 at 12:49
  • Is this list the product of something, or is it just a constant list you are handling as a list because you want this automated checking? If this list is just constant, I would agree with exceptions. If it is already a list, I would use some variant of reduce(). BTW, you cannot modify the error_code you passed in, so I am not sure I follow your example. – Jon Jay Obermark Aug 27 '14 at 21:57
  • @JonJayObermark I found a workaround with exceptions, though now that I have some more Python experience, I think I'd rather use decorators. – Nobilis Aug 28 '14 at 8:21
  • 1
    Using exceptions for exactly this is the norm. Even if you use a decorator, you probably want to do what the original comment suggested and use the mechanisms together. The decorator would probably just check all of the places different systems might leave error information and choose the most meaningful exception to throw. Basically, I am saying that is not a workaround, it is standard practice. – Jon Jay Obermark Aug 28 '14 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.