MrFox
MrFox

Reputation: 1254

Python getattr() member or function?

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.

Upvotes: 4

Views: 1807

Answers (3)

robert
robert

Reputation: 34398

Use the callable function:

if hasattr(o, required_field):
    v = getattr(o, required_field):
    if not callable(v):
        print "found field", required_value, "for value", v

In Python 3, use isinstance(obj, collections.Callable) (after import collections, of course). Also, it appears callable was added back in Python 3.2.

Upvotes: 4

Silas Ray
Silas Ray

Reputation: 26160

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

alternate:

if callable(value):
    value = value()

also:

import types
if isinstance(value, types.GeneratorType):
    # Handle generator case

Upvotes: 5

Mark Grey
Mark Grey

Reputation: 10257

Assuming a call to the method would be safe:

methods = []
properties = []

if hasattr(o,required_field):
  value = getattr(o,required_field)
  try:
     #see if this value is callable
     value()
     methods.append(value)
  except TypeError:
     #property is not a method
     properties.append(value)

Upvotes: 3

Related Questions