Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python getattr() member or function?

Tags:

python

I'm trying to use Python's getattr() to extract data out of a number of objects that I got from various APIs that I do not control. My idea was to go through a list of hetrogenous objects and try to getattr() on them until I pull out everything that I need.

So I'm doing one of these:

if hasattr(o, required_field):
    value = getattr(o, required_field)
    result.append([required_field, value])
    print 'found field', field, 'for value', value

My problem is sometimes the objects I'm dealing with have object.data() and sometiems object.data to pull stuff out. Sometimes these objects are actually generators.

So once in a while I'd get something like this:

found field ValueOfRisk for value
CellBM:<Instrument:/limbo/WLA_YdgjTdK1XA2qOlm8cQ==>.ValueOfRisk>

Question: is there a way that I can say 'access the data member when it's a data member, or call a function when it's a function' to take the value out of these things? Seems like this should be easy with Python but I can't find it.

like image 624
MrFox Avatar asked Dec 15 '22 22:12

MrFox


1 Answers

if hasattr(value, '__call__'):
    value = value()

alternate:

if callable(value):
    value = value()

also:

import types
if isinstance(value, types.GeneratorType):
    # Handle generator case
like image 58
Silas Ray Avatar answered Dec 29 '22 14:12

Silas Ray