view raw
jturmel jturmel - 1 year ago 50
Python Question

Specifying object property in dot notation with a variable

Is it possible to access a property/method on a Python object with a variable and how?



I'd like to replace the 'GET' part by capturing the method beforehand into a variable and then using it in the dot notation.

method = handler.method

I just can't see where/how to do that.


You are looking for getattr:

getattr(handler.request, 'GET') is the same as handler.request.GET.

So you can do

method = "GET"
getattr(handler.request, method).add()