Home > Blockchain >  Raise an exception if a variable is not defined in Python Class
Raise an exception if a variable is not defined in Python Class

Time:03-29

I am required to make a FancyTuple class and optionally pass five values as I want, the FancyTuple class should return a specific value when accessed, for example when I pass:

  • FancyTuple('dog','cat').first , it should return dog as dog is the first value passed.
  • FancyTuple('dog','eagle','mouse).third should return mouse as mouse is the third element passed.

However when a non-initialized variable is accessed it should Raise an exception of variable not defined, example:

  • FancyTuple('dog','cat').fifth , it returns an Exception because fifth has not been defined now.

How may I implement this? What I have been trying until now was to initialize in __ init__ and then in __str __ method I was trying to implement the null value but it is not working properly. I also tried __getattribute __ method but it gave a recursive code error?

The code is below:

class FancyTuple:
   def __init__(self, first = None, second = None, third = None, fourth = None, fifth = None):
        self.first = first
        self.second = second
        self.third = third
        self.fourth = fourth
        self.fifth = fifth


  def __str__(self, value):
      print('Value')
      if value == None:
          raise AttributeError('Accessed var is none')
    
      return f'{self.first} {self.second} {self.third} {self.fourth} {self.fifth}'

CodePudding user response:

The only point here is being aware of __getattribute__ is going to be invoked for any attribute access and the __getattr__ is going to be responsible for handling illegal attribute accesses.

class FancyTuple:
    def __init__(self, first = None, second = None, third = None, fourth = None, fifth = None):
        self.first = first
        self.second = second
        self.third = third
        self.fourth = fourth
        self.fifth = fifth
    
    def __getattribute__(self, attr):
        temp = object.__getattribute__(self,attr) 
        if temp == None:
            raise Exception("Your custom exception for None attributes")
        else:
            return temp
        
    def __getattr__(self, attr):
        raise AttributeError("Your custom exception for non-existing attributes")

    def __str__(self):
        return f'{self.first} {self.second} {self.third} {self.fourth} {self.fifth}'

Test 1:

myObject = FancyTuple('dog','eagle','mouse', 'foo', 'bar')
print(myObject)
print(myObject.fifth)
print(myObject.sixth)

Output:

dog eagle mouse foo bar
bar

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-41-b04d601ed000> in <module>()
      2 print(myObject)
      3 print(myObject.fifth)
----> 4 print(myObject.sixth)

<ipython-input-40-747793c9a3b8> in __getattr__(self, attr)
     15 
     16     def __getattr__(self, attr):
---> 17         raise AttributeError("Your custom exception for non-existing attributes")
     18 
     19     def __str__(self):

AttributeError: Your custom exception for non-existing attributes

Test 2:

myObject = FancyTuple('dog','eagle','mouse', 'foo')
print(myObject.fifth)

Output:

---------------------------------------------------------------------------

Exception                                 Traceback (most recent call last)

<ipython-input-42-2a980f7d7d01> in <module>()
      1 myObject = FancyTuple('dog','eagle','mouse', 'foo')
----> 2 print(myObject.fifth)

<ipython-input-40-747793c9a3b8> in __getattribute__(self, attr)
     10         temp = object.__getattribute__(self,attr)
     11         if temp == None:
---> 12             raise Exception("Your custom exception for None attributes")
     13         else:
     14             return temp

Exception: Your custom exception for None attributes
  • Related