Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flattening attribute access
#2
Instead of this:
        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}')
Reply


Messages In This Thread
Flattening attribute access - by ruy - Jun-25-2021, 12:09 PM
RE: Flattening attribute access - by deanhystad - Jun-25-2021, 01:18 PM
RE: Flattening attribute access - by ruy - Jun-25-2021, 01:44 PM
RE: Flattening attribute access - by deanhystad - Jun-25-2021, 07:19 PM
RE: Flattening attribute access - by ruy - Jun-25-2021, 08:18 PM
RE: Flattening attribute access - by ruy - Jun-25-2021, 08:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  sharepoint: Access has been blocked by Conditional Access policies CAD79 0 2,402 Jul-12-2024, 09:36 AM
Last Post: CAD79
  How to access parent object attribute Pavel_47 2 12,329 Nov-19-2021, 09:36 PM
Last Post: deanhystad
  Problem in flattening list Shahmadhur13 5 3,609 May-03-2020, 12:40 AM
Last Post: DeaD_EyE
  Is it OK to use a context manager to simplify attribute access? nholtz 0 2,596 Jun-11-2019, 01:19 AM
Last Post: nholtz
  flattening a list with some elements being lists Skaperen 17 10,634 Apr-09-2019, 07:08 AM
Last Post: perfringo
  Flattening List mp3909 8 6,705 Jan-26-2018, 12:13 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020