Reputation: 305
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.
Upvotes: 20
Views: 16499
Reputation: 251468
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()
Upvotes: 29
Reputation: 34718
You could do something like getattr
getattr(handler.request, "GET").add()
Then just do
method = "GET" # or "POST"
getattr(handler.request, method).add()
Upvotes: 2
Reputation: 1123510
Use the getattr()
function to access dynamic attributes:
method = 'GET'
getattr(handler.request, method).add()
which would do exactly the same thing as handler.request.GET.add()
.
Upvotes: 6