0

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'

RRR
  • 69
  • 6

2 Answers2

1

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
>>>
0

getattr(getattr(value, 'number'), 'odd')

Or taken from Python - getattr and concatenation by Cat Plus Plus

def getattr_deep(start, attr):
    obj = start
    for part in attr.split('.'):
        obj = getattr(obj, part)
    return obj

getattr_deep(foo, 'A.bar')
Community
  • 1
  • 1
wallacer
  • 12,855
  • 3
  • 27
  • 45
  • I understand that, but I thought there would be a simpler way without splitting 'number' and 'odd'. The input value x varies from a vast range of values. Some are even value.number.negative.odd – RRR Jun 19 '14 at 19:11
  • Ah, that's fair. I don't believe there's a built-in way, but the duplicate of your question has a solution that will work for you – wallacer Jun 19 '14 at 19:12