Python Deep setter
from operator import attrgetter
def deep_setter(obj, aliases: list, value):
"""
>>> class C():
>>> pass
>>> class B():
>>> c = C()
>>> class A():
>>> b = B()
>>> a = A()
>>> deep_setter(a, ["b", "c"], "test")
>>> a.b.c
'test'
"""
if not isinstance(aliases, list):
raise TypeError("Alias must be a list")
if len(aliases) < 1:
raise ValueError("Alias list must be longer then 0")
if any(["." in el for el in aliases]):
raise ValueError("Elements can not contain dots")
if len(aliases) > 1:
last = aliases.pop()
dot_view = '.'.join(aliases)
get_penult = attrgetter(dot_view)
setattr(get_penult(obj), last, value)
else:
setattr(obj, aliases[0], value)
Concerned Cow