Search code examples
pythongetattr

How can I use getattr to access an attribute within an attribute?


What I have is a value found in:

value.number.odd = 7

number.odd is an input by the user, in x.

and so if x='number.odd', I was hoping that:

getattr(value, x)

would display what value.number.odd would, but it doesn't. Instead I get:

AttributeError: missing attribute number.odd

EDIT:

Input x can also be something like X='number', or 'number.negative.prime'


Solution

  • You can use reduce for this (functools.reduce in Python 3.x):

    reduce(getattr, x.split('.'), value)
    

    See a demonstration below:

    >>> class A:
    ...     def __init__(self):
    ...         self.odd = 7
    ...
    >>> class B:
    ...     def __init__(self):
    ...         self.number = A()
    ...
    >>> value = B()
    >>> value.number.odd
    7
    >>> x = 'number.odd'
    >>> reduce(getattr, x.split('.'), value)
    7
    >>>