Search code examples
pythondeep-copy

Returning self.__dict__ from a method


I am working with a nice little python module from a third party, and I ran across a bit that has got my brain all twisted, and I'm mostly concerned with data integrity.

Quick summary: there is a class method that goes roughly as such:

def as_dict(self):
    ##adjust some attributes that don't make sense outside this scope        
    ##... ... ...
    return self.__dict__

I am manually using the result of this method, but there are a few places where I pass it on, and I have no idea what those function are actually doing to the returned dict.

Now, is this safe as it is, or could some stray function start messing with my instance attributes? I originally thought that 'self' somehow protected the dataset, and I was passing around a copies of the data, but now I wonder if I am passing around references to instance memory? (there are nested mutables within)

Should I just do instead: return copy.deepcopy(self.__dict__)


Solution

  • You're correct, the instance dict is perfectly mutable like any other dict. It's unusual to return the dict like that. Perhaps it's indended to be modified outside the instance for some reason. Seems like it's probably a bad design though.

    Sometimes people do horrible things like that because they think it's better than using global variables.

    Copying isn't really a good fix. It could be very slow, and is just hiding the underlying design problems

    An alternative to copying would be to wrap the dict so it can't be modified accidentally.