1

I have an inheritance hierarchy whereby some of the classes have a class property named e.g., 'pickled'. I would like to get A.pickled if it exists or None if not — even if A derives from many classes including e.g., B and B.pickled exists (or not).

Right now my solution crawls A's __mro__. I would like a cleaner solution if possible.

Neil G
  • 32,138
  • 39
  • 156
  • 257
  • What problem are you trying to solve? – SingleNegationElimination Jun 10 '14 at 21:08
  • @IfLoop I am using the class property to automatically pickle particular properties. I am also using another class property to automatically generate a user interface, and yet more class properties to automatically generate histories of parameter values. Do you have a better solution? – Neil G Jun 10 '14 at 21:11

2 Answers2

2

To bypass the normal search through the __mro__, look directly at the attribute dictionary of the class instead. You can use the vars() function for that:

return vars(cls).get('pickled', None)

You could just access the __dict__ attribute directly too:

return cls.__dict__.get('pickled', None)

but using built-in functions is preferred over direct access to the double-underscored attribute dictionary.

object.__getattribute__ is the wrong method to use for looking at class attributes; see What is the difference between type.__getattribute__ and object.__getattribute__?

type.__getattribute__ is what is used for attribute access on classes, but that'd still search the MRO too.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

I'm not sure, but perhaps

try:
    return object.__getattribute__(cls, 'pickled')
except AttributeError:
    return None
Neil G
  • 32,138
  • 39
  • 156
  • 257