Jun-25-2021, 01:18 PM
(This post was last modified: Jun-25-2021, 01:22 PM by deanhystad.)
Instead of this:
I don't know if using __getattr__ this way is good or bad, but I do something similar in some code I am working on, and while researching have found other places where this is done. It is not an unusual use of __getattr__.
If you are going to reference multiple objects this way be aware that you will need to handle exceptions. For example, if your class has internal objects "object_a" and "object_b", this complicates things.
try: return getattr(self.meta_data, name) except AttributeError: return self.__getattribute__(name)You should simply do this:
return getattr(self.meta_data, name)__getattr__ is only called if "name" cannot be resolved by normal means. So if "name" is an attribute of PrintValue, __getattr__ is not called. Worse, by catching the error and calling self.__getattribute__(name), any "name" that is not an attribute of the PrintValue object or the PrintMetaData object results in a recursion of caught exceptions.
I don't know if using __getattr__ this way is good or bad, but I do something similar in some code I am working on, and while researching have found other places where this is done. It is not an unusual use of __getattr__.
If you are going to reference multiple objects this way be aware that you will need to handle exceptions. For example, if your class has internal objects "object_a" and "object_b", this complicates things.
def __getattr__(self, "name"): while part in (self.object_a, self.object_b): try: return getattr(part, name): except NameError: pass: raise NameError(f'{self.__class__.__name__} does not understand {name}')