1 year ago
#76218
Space Squid
Remove/alter object reference in dictionary created with vars() or __dict__
I am working on a way to serialize complex objects into JSON. This includes objects that have other objects as attributes. I have run into a problem with my current approach that has piqued my interest:
When I have an object with at least one attribute that is also a custom object and I call the vars()
function on it, it returns the object as a dictionary containing a reference to the object in the attribute rather than - what I naively expected - the representation as string (i.e. {"attribute": <object object at ...>}
as opposed to {"attribute": "<object object at ...>"}
. While this is expected behavior it has lead me to a problem:
If I now want to delete the entry with the object reference as value from the dictionary or alter it in any way, all actions taken on it of course affect the referenced object as well. That means any action taken onto the dictionary also affect the original object from which the dictionary was created. For example using object.vars().pop("attribute")
deletes the attribute not only in the dictionary, but in object
as well. I have a small minimal example below.
My question is the following: is there an elegant way to still change and/or delete the entry for the object attribute in the dictionary without changing/deleting the original object that the dictionary points to?
I am aware that I can use the deepcopy function from the copy module to circumvent the issue by creating a deep copy and altering only this copy - that is what I am currently doing. But the question piqued my interest as I thought there might be a clever, more "pythonic" way to deal with this.
Minimum working code example:
class A:
def __init__(self):
self.attribute = object()
a = A() # create an object with object attribute
print(a.attribute) # prints <object object at ...>
d = vars(a) # contains key "attribute" with reference to a as value
d.pop("attribute")
print(a.attribute) # raises AttributeError
python
python-3.x
oop
reference
0 Answers
Your Answer