Serialize a Class Object using vars()?

Question:

beginner with Python here !

When serializing an instance in Python I tried using vars(), which returns returns the dict of said instance.

class Foo:
    def __init__(self, doc_id, name):
        self.doc_id = doc_id
        self.name = name

user1 = Foo(3, "Eddy")

serialized = vars(user1)

print("user1", user1.__dict__)
print("serialized", serialized)

So far so good.

user1 {'doc_id': 3, 'name': 'Eddy'}
serialized {'doc_id': 3, 'name': 'Eddy'}

I thought that serialized was now a dict with {key: value} copied from the instance user, but if I change a value like this:

serialized["name"] = Jo

It reverts the changes back to the instance.

print("serialized", serialized)
print("user1", user1.__dict__)
serialized {'doc_id': 3, 'name': 'Jo'}
user1 {'doc_id': 3, 'name': 'Jo'}

My two questions are:

  • is vars() only use is to read attributes and not getting those attributes to modify them or am I missing something ?
  • do I have to create my own method / function to create my dict if I want to tweak the value ?

thanks !

Asked By: JBT

||

Answers:

Firstly, in Python, the vars() function returns the __dict__ attribute of an object, which is a dictionary containing the object’s attributes and their values. If the object has no dict attribute, an exception is raised. So that is all there is to it in this regard.

Then, when you have done serialized["name"] = 'Jo' (note the code in the question misses the quotes there) you have now change the value in the dict. So you should expect the dict to be modified.

So the result is:

serialized {'doc_id': 3, 'name': 'Jo'}
user1 {'doc_id': 3, 'name': 'Jo'}

And presumably this is desired (ie. what else are you trying to achieve) ?

In answer to the second question:
Yes, this is certainly an option and a more common way of changing the values.

Answered By: D.L

Thank you for this somehow controversional question.
According to python docs:

Objects such as modules and instances have an updateable dict attribute; however, other objects may have write restrictions on their dict attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates).

So since you’ve accessed dict variable of that object, you are allowed to have direct updates on it.

Answered By: Zar Ashouri
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.