vars() returns an object’s attribute dictionary
vars(obj) returns the object’s __dict__, the dictionary that holds its attributes:
class Order:
def __init__(self, customer, total):
self.customer = customer
self.total = total
order = Order("Ava", 120)
print(vars(order)) # {'customer': 'Ava', 'total': 120}
For an instance, the dictionary that vars() returns is the object’s own, not a copy. Changing it changes the object’s attributes. Modules and classes also have a __dict__.
With no argument, and when it fails
Without an argument, vars() acts like locals(). It returns the names in the current scope.
If the object has no __dict__, vars() raises TypeError. Numbers and strings do not have one:
vars(120) # TypeError
Instances of a class that defines __slots__ usually have no __dict__ either, so vars() raises the same error for them.
Passing named values to an SQL query
One use is to pass an object’s attributes into a named SQL query. The argparse namespace from a command-line script works well as an example, because each option becomes an attribute:
import argparse
import sqlite3
parser = argparse.ArgumentParser()
parser.add_argument("--customer")
parser.add_argument("--min-total", type=float, default=0)
args = parser.parse_args()
conn = sqlite3.connect("shop.db")
cur = conn.cursor()
cur.execute(
"SELECT id, total FROM orders WHERE customer = :customer AND total >= :min_total",
vars(args),
)
rows = cur.fetchall()
The option --min-total becomes the attribute min_total, which matches the placeholder. sqlite3 ignores extra keys in the dictionary, so other options do not cause an error. A placeholder with no matching key does raise an error.
If the user does not pass --customer, its value is None. A comparison with NULL never matches, so the query returns no rows. The placeholders still keep the query safe, because vars() only supplies the values.
Where vars() does not help
vars() gives you a dictionary of names and values. A list of values is not a name-value pair, so it does not fit this pattern. For lists, see how to pass a list of strings in SQL query. For the wider picture of passing values into SQL from Python, see how to pass variable in sql query in python.