Search code examples
pythontype-safety

How to convert a Python dict to a Class object


I am looking for a simple way to directly convert a python dict to a custom object as follows, while not breaking intellisense. The result should not be read-only, it should behave just like a new object.

d = {
    "key1": 1,
    "key2": 2
}

class MyObject(object):
    key1 = None
    key2 = None

# convert to object o

# after conversion
# should be able to access the defined props
# should be highlighted by intellisense
print(o.key1)
# conversion back to dict is plain simple
print(o.__dict__)

Solution

  • Your object has no fields, just class attributes. You need to create a __init__ method, some will call it a constructor but it is not actually a constructor as understood by other languages so lets avoid calling it like that.

    class MyObject:
        def __init__(self, d=None):
            if d is not None:
                for key, value in d.items():
                    setattr(self, key, value)
    
    d = {
        "key1": 1,
        "key2": 2,
    }
    
    o = MyObject(d)
    

    Note: the above code will try to set all key-value pairs in the dict to fields in the object. Some valid keys such as "key.1" will not be valid field names (it will actually be set but you will not be able to get it with o.key.1).