2

Is there a way to loop over attributes, without retyping a long name?

I'm trying to print the value(s) stored in an object. The problem is that I don't know what attribute stores the value, or even what the attributes are. I used dir(MyFunc) to find what the attributes are, but every time, there are more and more attributes to look through.

>>> print dir(MyFunc)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', 'data']

>>> print dir(MyFunc.data)
['__call__', '__class__', '__closure__', '__code__', '__defaults__',
'__delattr__', '__dict__', '__doc__', '__format__', '__get__',
'__getattribute__', '__globals__', '__hash__', '__init__', '__module__',
'__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure',
'func_code', 'func_defaults', 'func_dict', 'func_globals', 'func_name']

So I tried to use a for loop to print the attributes of each attribute, but I can't find how to do this.

>>> for x in ['func_closure','func_code','func_defaults','func_dict']:
        y = MyFunc.data.x
        print y
Traceback (most recent call last):
File "myFile.py", line 127, in setUp
y = MyFunc.data.x
AttributeError: 'function' object has no attribute 'x'
Sean
  • 23
  • 3

1 Answers1

0

Use getattr

for x in ['func_closure','func_code','func_defaults','func_dict']:
     y = getattr(MyFunc.data,x)
     print y
NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37