Home > Blockchain >  python 3.x - How to return None from class creation
python 3.x - How to return None from class creation

Time:09-30

I am passing a dictionary to a class which maps the dictionary to a class object. This works successfully when the dict is correct. However, I want the class to return None when there is an issue, like an unexpected Key in the dictionary.

In the t_bf_obj class code below, if an unknown dict key exists the class does not return None , it returns a t_bf_obj object. One additional observation, the message in the exception is printed 'Exception in t_bf_obj' so I know the exception is called.

class bf_exception(Exception):
   pass

class t_bf_obj():
    unit  = None
    index = None
    U_c   = None
    
    def __init__(self,dict:dict):
        try:
            for k, v in dict.items():
                if  (k=='unit')  : self.unit = str(v)
                elif(k=='index') : self.index = int(v)
                elif(k=='U_c')   : self.U_c = np.array(v)
                else:
                    raise bf_exception()            
            
        except bf_exception as e:
            print('Exception in t_bf_obj')
            return None 

In main code:

        # convert dict to t_bf_obj
        obj = t_bf_obj(d_dict)
        print(type(obj)) # <------------returns t_bf_object type when unknown key is in dict
        if(obj is None):
            print('Error: ThreadedTCPRequestHandler, obj==None',type(obj))
            return

CodePudding user response:

A better approach would be to avoid instantiating the class in the first place if the dict is in valid. You can accomplish this via a class method.

class t_bf_obj:    
    def __init__(self, unit: str, index: int, u_c: np.array):
        self.unit = unit
        self.index = index
        self.U_c = u_c
    
    @classmethod
    def from_dict(cls, dict):
        for k, v in dict.items():
            if k == 'unit':
                unit = str(v)
            elif k == 'index':
                index = int(v)
            elif k == 'U_c':
                u_c = np.array(v)
            else:
                raise bf_exception()

        return cls(unit, index, u_c)

try:
    obj = t_bf_obj.from_dict(d_dict)
except bf_exception:
    # If we're here, obj is undefined; no object was returned
    # by t_bf_obj.from_dict
    print('Error: ThreadedTCPRequestHandler')

CodePudding user response:

I solved my issue by adding an error parameter in the class which helps to track the state of health of the object during creation:

class t_bf_obj():   
    def __init__(self,dict:dict):
        self.unit  = None
        self.index = None
        self.U_c   = None
        self.init_err = 0
    
        try:
            for k, v in dict.items():
                if  (k=='unit')  : self.unit = str(v)
                elif(k=='index') : self.index = int(v)
                elif(k=='U_c')   : self.U_c = np.array(v)
                else: self.init_err = 1     
            
        except: 
            print('Exception in t_bf_obj')
            self.init_err = 1
            return

In the main program:

    obj = t_bf_obj(d_dict)
    if(obj is None or obj.init_err == 1):
        print('Error: obj is None or obj.init_err = 1')
        return
  • Related