Hacker News new | ask | show | jobs
by akubera 2685 days ago
I can't think of a single time I've needed a large collection of "backup" methods in case of a chain of failures; I can't even think of an example which could scale to 100. Anyways, this solution does scale:

    methods = [method1, method2, method3, method4]
    for method in methods:
        try:
            method()
        except Exception:
            pass
        else:
            break
    else:
        raise NoMethodWorked()
You can even pair specific exceptions to each method:

    methods = [(method1, TypeError), (method2, KeyError)]
    for m, e in methods:
       try: m()
       except e: ...
But the whole thing really sounds like you're trying to do too much with one function and you really should rethink the whole structure of your code.
1 comments

This is really helpful. Thank you.