jturmel
jturmel

Reputation: 305

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.

Upvotes: 20

Views: 16499

Answers (3)

BrenBarn
BrenBarn

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

Jakob Bowyer
Jakob Bowyer

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

Martijn Pieters
Martijn Pieters

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

Related Questions