python passing a variable to an object property or method through a function argument
Question
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
Solution
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