Oh What A Noob
Oh What A Noob

Reputation: 507

How to access self.context property using a variable in flask

I want to access a property exist in the self.context using a variable. I have a variable name "prop" and it contains a value and it is already set in the self.context. I am using Flask Restplus framework.

prop = 'binding'

If I try to access this property like below then it gives me an error:

Object is not subscriptable

I want to know if there is any way to get the value? Like doing this:

print(self.context[prop])

I only get one solution don't know if its correct or not, I tried this :

self.context.__getattribute__(prop)

Upvotes: 0

Views: 347

Answers (1)

There are two ways to do this, the simplest is using getattr:

getattr(self.context, prop)

This function internally calls __getattribute__ so it's the same as your code, just a little neater.

However, you still have the problem that you probably only want to access some of the context, while not risking editing values set by different parts of your application. A much better way would be to store a dict in context:

self.context.attributes = {}
self.context.attributes["binding"] = False
print(self.context.attributes[prop])

This way, only certain context variables can be accessed and those that are meant to be dynamic don't mess with any used by your application code directly.

Upvotes: 1

Related Questions