2

I've been trying to construct a generic function (a Django view handler) whose arguments are contains specific object property to use inside the function

something like (simplified):

def some_function(arg, property):
    return Some_Object.property

but python tries to treat 'property' as the property/method name instead of treating it like a variable.

I tried multiple variants but none worked. (didn't try exec/eval varient - should I? doesn't seem too pythonic)

I know that I can pass a function or an object as an argument. but didn't seem to find the exact solution here using python 2.7 and 2.6

the specific implantation is a Django issue but I got curious about this

alonisser
  • 11,542
  • 21
  • 85
  • 139
  • `eval` considered harmful http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice – msw Jun 09 '12 at 22:13

1 Answers1

6

I think what you want to do is use getattr to retrive the property:

def some_function(arg, property):
    return getattr(Some_Object, propery)

You can see the documentation here: http://docs.python.org/library/functions.html#getattr

Trevor
  • 9,518
  • 2
  • 25
  • 26