Search code examples
pythonexceptiontry-catchexceptgeneralization

good way to generalize multiple try except


I have 15 try except statements in a for loop in the code. I think that it can be generalized but I am not able to get to the solution. How can I do it.

for item in results:

    try:
        a = item.something()
    except:
        a = ""

    try:
        b = item.something2()
    except:
        b = ""

    b = re.sub(r'\W+', ' ', b)
    b = b.strip()

    try:
        c = item.something3()
        parsed_url = urlparse(b)
        if not bool(parsed_url.scheme):
            break
    except:
        c = ""

    try:
        d = item.something4()
    except:
        d = ""

As suggested in the answer I generalized it to

def attrs(self, call_fun):
    try:
        return call_fun()
    except:
        return ""

But when I call

   a = self.attrs(item.get("data-a")) 

I get a blank output whereas calling try: except: gives correct output. Whats going wrong?


Solution

  • Without changing your data:

    def try_something(callable):
        try:
            return callable()
        except:
            return ""
    
    a = try_something(item.something)
    

    Remember that you can freely pass a callable (function or method) as a parameter to a Python function. This utilizes that. However, there may still a better way to do this by refactoring the class of item, but that would require more information.

    Also, do you not know the type of exception being thrown? If you do, you should be more explicit in the except statement.