0

I am working on a class that has attributes depending from one another. When instantiated, the class should try to initiate all the attributes it can but is should skip the ones raising an exception.

Something like this:

def foo:
    def __init__(self, a, b, c):
        try: self.x = len(a)
        except: pass
        try: self.y = sum(b)
        except: pass
        try: self.z = c
        except: pass
        try: self.v = self.x + self.z
        except: pass
        try: self.w = self.x + self.y
        except: pass
    
    

This works but it looks horrible. Is there a way to simplify this process?

Is there a way to achieve the same result with a cleaner code like the following?

def foo:
    def __init__(self, a, b, c):
        try:
            self.x = len(a)
            self.y = sum(b)
            self.z = c
            self.v = self.x + self.z
            self.w = self.x + self.y
        except:
            continue_to_the_next_line()
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • Why don't you check the datatypes of a,b,c before performing the mathematical operation. If they don't satisfy the datatype, then just ignore. – Epsi95 Jan 23 '21 at 13:32
  • Because it's too much code and wouldn't be much better than the try/except solution. I am looking for something really straight forward. What I am looking for is a way to just skip the attributes is it gives error. – alec_djinn Jan 23 '21 at 13:36
  • I don't think a piece of code doesn't needs to be aesthetically pleasing. – Shambhav Jan 23 '21 at 13:40
  • Does this answer your question? [Multiple try codes in one block](https://stackoverflow.com/questions/17322208/multiple-try-codes-in-one-block) – costaparas Jan 23 '21 at 13:46
  • 2
    There aren't a lot of neat ways to do it in this case, but if you check the linked post, I quite like the solution using the [`fuckit` module](https://stackoverflow.com/a/50051815/14722562) (yes, that's what its called). – costaparas Jan 23 '21 at 13:47
  • 1
    @costaparas It is a valuable solution – alec_djinn Jan 23 '21 at 14:04
  • This smells like a scenario for [property getter/setters](https://www.geeksforgeeks.org/python-property-function/). I'm assuming that you are looking for _cleaner_ code, not _shorter_. – Pavel Jan 23 '21 at 14:03
  • @Pavel I am trying to get rid of the boilerplate code. Getter, setters, property, try/except... They all look like boilerplate to me when I try using them in the specified example. The fuckit module is the only decent solution I have found so far. I am not a fan of installing a library for a single case, so I am still interested in vanilla-Python examples. – alec_djinn Jan 28 '21 at 12:30

0 Answers0