From an external webservice I receive a JSON response that looks like this (for convenience, it is already deserialized below):
alist = [
{
'type': 'type1',
'name': 'dummy',
'oid': 'some_id'
},
{
'type': 'type2',
'name': 'bigdummy',
'anumber': 10
}
]
For each type
there exists a class. What I want is to instantiate objects of the respective class without using a long list of if-elif
s.
I tried as follows:
Define classes A
(for type1
) and class B
(for type2
) using a from_dict
classmethod
:
class A():
def __init__(self, name, oid, optional_stuff=None):
self.name = name
self.oid = oid
self.optional_stuff = optional_stuff
@classmethod
def from_dict(cls, d):
name = d['name']
oid = d['oid']
optional_stuff = d.get('optional_stuff')
return cls(name, oid, optional_stuff)
def foo(self):
print('i am class A')
class B():
def __init__(self, name, anumber):
self.name = name
self.number = anumber
@classmethod
def from_dict(cls, d):
name = d['name']
anumber = d['anumber']
return cls(name, anumber)
Then I define a mapping dictionary:
string_class_map = {
'type1': A,
'type2': B
}
and finally convert alist
to something the from_dict
functions can easily consume:
alist2 = [
{
di['type']: {k: v for k, v in di.items() if k != 'type'}
}
for di in alist
]
[{'type1': {'name': 'dummy', 'oid': 'some_id'}},
{'type2': {'name': 'bigdummy', 'anumber': 10}}]
object_list = [
string_class_map[k].from_dict(v) for d in alist2 for k, v in d.items()
]
That gives me the desired output; when I do:
a = object_list[0]
a.name
will indeed print 'dummy'
.
Question is whether there is a better way of getting from alist
(this input I cannot change) to object_list
.