Task: setattr(self, key, value) if hasattr(self, key) else setattr(otherobject, key, value)
where otherobject
is an attribute of self
The problem has two problems that I am unable to solve.
setattr(self.baz, key, value)
ends badly if__setattr__
is re-defined, because you cannot assignself.baz
without calling__setattr__
which requiresself.baz
to be defined.I want the behavior of
__getattr__
(called when the default attribute access fails) in my__setattr__
(called when an attribute assignment is attempted) where it is only called when hasattr(self, key) is False.
The below code is wrong; I expect that the solution will resemble...
def monkeypatchsetattr(obj, oldsetattr):
def newsetattr(key, value):
# hasattr(self, key) will return true if key is an attrib of baz
# and so is not a good test
if key is self.__dict__:
oldsetattr(key, value)
else:
setattr(obj.baz, key, value)
return newsetattr
class Baz():
pass
class Qux():
def __init__(self):
self.name = None
self.color = 'red'
self.baz = Baz()
self.__setattr__ = monkeypatchedselfattr(self, self.__setattr__)
def __getattr__(self, item):
return getattr(self.baz, item)
def __setattr__(self, item, value):
if hasattr(self, item):
super(Qux, self).__setattr__(self, item, value)
else:
setattr(self.baz, item, value)
Problem 1 is the bigger and more immediate problem.
Is there a more elegant solution to Problem 2 after Problem 1 is resolved?