The built-in vars(obj)
returns a dict with key/values mirroring the attributes of obj
. Is there an inverse of this function? I.e. a function that takes a dictionary and returns an object.
I've come up with two ways of doing it, neither of which would be obvious to someone reading it. The first version involves assigning a new dict to self.__dict__
:
class _Tmp(object):
def __init__(self, dct):
self.__dict__ = dct
obj = _Tmp({'hello': 'world'})
assert obj.hello == 'world'
and the second version uses a non-standard call to the type
builtin:
obj = type('', (), {'hello': 'world'})
assert obj.hello == 'world'
Is there an easier/more readable way?
In Python 3.3 and up you can use types.SimpleNamespace
:
from types import SimpleNamespace
obj = SimpleNamespace(**{'hello': 'world'})
There is the module attrdict
that does what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With