jturmel jturmel - 6 months ago 19
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?

Example:

handler.request.GET.add()


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
handler.request.{method}.add()


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

Answer

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()
Comments