Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flattening attribute access
#1
Hi there

I have a class PrintValue that contains as attribute an instances of another class PrintMetaData. In order to acess an attribute of the PrintMetaData object I would have to do something like object.meta_data.attribute. I wanted to flatten the access to the attribute to object.attribute. I wrote a class to do that and was wondering if that is considered bad practice. Obviously there is the possibility of name conflicts if the classes have attributes with the same name, but I could live with that. Here an example:

from dataclasses import dataclass


@dataclass
class PrintMetaData:
    """Print meta data for attr."""

    long: str
    abbr: str
    unit: str = None
    round_precision: int = 2


@dataclass
class PrintValue:
    """Printer wrapper for value."""

    value: float
    meta_data: PrintMetaData

    def __getattr__(self, name):
        try:
            return getattr(self.meta_data, name)
        except AttributeError:
            return self.__getattribute__(name)


fwd_perp_md = PrintMetaData(
    "Foward perpendicular",
    r"F\textsubscript{P}",
    "m"
)
fwd_perp_value = PrintValue(10, fwd_perp_md)
print(fwd_perp_value.meta_data)
print(fwd_perp_value.long)
print(fwd_perp_value.abbr)
print(fwd_perp_value.unit)
print(fwd_perp_value.round_precision)
This is small and seems to work, but I was wondering if that is still ok with classes with more internal objects.
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,021 Jul-12-2024, 09:36 AM
Last Post: CAD79
  How to access parent object attribute Pavel_47 2 11,845 Nov-19-2021, 09:36 PM
Last Post: deanhystad
  Problem in flattening list Shahmadhur13 5 3,376 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,495 Jun-11-2019, 01:19 AM
Last Post: nholtz
  flattening a list with some elements being lists Skaperen 17 9,990 Apr-09-2019, 07:08 AM
Last Post: perfringo
  Flattening List mp3909 8 6,384 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