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:
a = item.something()
a = ""
b = item.something2()
b = ""
b = re.sub(r'\W+', ' ', b)
b = b.strip()
c = item.something3()
parsed_url = urlparse(b)
if not bool(parsed_url.scheme):
c = ""
d = item.something4()
d = ""
def attrs(self, call_fun):
a = self.attrs(item.get("data-a"))
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