Setting object properties in dotted variable notation

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

Example:

handler.request.GET.add() 

I would like to replace the β€œGET” part by first running the method in a variable and then using it in the point notation.

 method = handler.method handler.request.{method}.add() 

I just don't see where / how to do this.

+6
source share
3 answers

You are looking for getattr :

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

So you can do

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

Use the getattr() function to access dynamic attributes:

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

which will do the same as handler.request.GET.add() .

+5
source

You can do something like getattr

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

Then just do

 method = "GET" # or "POST" getattr(handler.request, method).add() 
+2
source

All Articles