Home > Software engineering >  del on field from vars(instance) removes property from object
del on field from vars(instance) removes property from object

Time:10-23

I noticed a very strange behaviour:

class Aclass:
    def __init__(self, time: int, contract: Contract, strategy: str = 'Strategy') -> None:
        self.time: int = time
        self.contract: Contract = contract
        self.strategy: str = strategy
    
    def to_dict(self) -> Dict:
        basic = vars(self)

        # I don't want this in the result 
        del basic['contract']

        return basic


if __name__ == '__main__':
    inst = Aclass(123, Contract())
    inst_dict = inst.to_dict()

    inst.contract # AttributeError: 'Aclass' object has no attribute 'contract' 


I get the above written attribute error... Any ideas why this happens?

If I use vars(self).copy() everything works fine.

CodePudding user response:

vars(self) returns the __dict__ attribute per the following documentation. The dictionary returned stores all of the attributes of the object instance. As a result, deleting one of the entries via del is equivalent to deleting the attribute of the object instance.

If you want to return a modified vars(self) without affecting the instance of the object, you will need to perform a copy.

  • Related