Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an inverse of `vars(object)`

Tags:

python

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?

like image 258
thebjorn Avatar asked Dec 11 '22 02:12

thebjorn


2 Answers

In Python 3.3 and up you can use types.SimpleNamespace:

from types import SimpleNamespace

obj = SimpleNamespace(**{'hello': 'world'})
like image 52
Martijn Pieters Avatar answered Jan 11 '23 22:01

Martijn Pieters


There is the module attrdict that does what you want.

like image 44
Dunes Avatar answered Jan 11 '23 22:01

Dunes