Python – vars

Parsing python function vars () from methods for dictionaries (dict).

Many classes python show the content in the form of a dictionary, but at the same time they are not a dictionary, but are an object of a class within which the data format can be represented __dict__

If you try to access such an object with the dictionary methods, errors will be thrown.

However, since such objects have attributes inside them __dict__, then you can convert them to a dictionary. And then work as with a regular dictionary.

Let’s look at an example

Request SQLAlchemy:

response = db.sessionquery(UserSetting)filter_by(user_id=user_id)order_by(asc(UserSetting.name))all()

By request type (response) we learn that response is an object list:

Through print (response) we will see the following content:

[[<1: analyze_sp500:120:None:1597834582>, <1: brent_oil:300:None:1597834559>]

Now let’s check the content of an individual element class list:

for s in response:
print(type(s))

We are shown that this is a model class ORM SQLAlchemycontaining data from the table UserSetting:

<class ‘app.models.UserSetting’>

We cannot work with it using dictionary methods. We need to convert it to a dictionary explicitly. For this we use the function vars () in Python:

for s in response:
setting = vars(s)
print(type(setting))

This is how we turned the contents of a part of an object into a dictionary:

Instead vars (s) can be used s .__ dict__, but the first option, as they say, is more “pythonist”.

Finally, let’s see what is inside the created dictionary:

for s in response:
setting = vars(s)
print(setting)

Instead of such a faceless data format:

<1: analyze_sp500:120:None:1597834582>

We’ll see:

{‘_sa_instance_state’: <sqlalchemy.ormstateInstanceState object at 0x11942c510>,
‘id’: 2,
‘name’: ‘analyze_sp500’,
‘percent’: None,
‘timer’: ‘120’,
‘timestamp’: 1597834582,
‘user_id’: 1}

Now we can use any methods of the dictionary and access the data in the usual way:
setting[‘name’]

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *