python passing a variable to an object property or method through a function argument

StackOverflow https://stackoverflow.com/questions/10964940

  •  13-06-2021
  •  | 
  •  

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

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top