Python vars() Function

Rate this post

Python’s built-in vars() function returns the __dict__ attribute of an object—a dictionary containing the object’s changeable attributes. Without argument, it returns the local symbol table similar to locals().

class Car:
    def __init__(self):
        self.speed = 100
        self.brand = 'porsche'

porsche = Car()
print(vars(porsche))
# {'speed': 100, 'brand': 'porsche'}

Python’s built-in vars() function returns a dictionary of name: value mappings of all the names defined in the local scope or the scope of the optional object argument, and their associated values.

  • When used without an argument, vars() returns the same as locals() that returns a dictionary of name --> object mappings of names defined in the current local scope and objects being their associated values.
  • When used with an object argument, vars(object) returns the same as object.__dict__() that returns a dictionary of name --> object mappings of writable names defined in the object’s scope and objects being their associated values.
Python vars() Function - Explanation + Example

Learn by example! Here’s an example on how to use the vars() built-in function.

Video vars()

vars() without Argument: Syntax and Example

Syntax: 
vars()         # Returns dictionary of "name --> value" mappings like locals()
Arguments-
Return ValuedictDictionary of mappings from variable names defined in the local namespace and the objects they’re referring to.

When used without an argument, vars() returns the same as locals() that returns a dictionary of name --> object mappings of names defined in the current local scope and objects being their associated values.

>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> vars() == locals()
True

vars() with Argument: Syntax and Example

Syntax: 
vars(object)         # Returns same as object.__dict__()
ArgumentsobjectObject for which the attribute name-object mappings should be retrieved
Return ValuedictDictionary of mappings from attribute names defined in the object’s namespace and the objects they’re referring to.

When used with an object argument, vars(object) returns the same as object.__dict__() that returns a dictionary of name --> object mappings of writable names defined in the object’s scope and objects being their associated values.

>>> def f():
	x = 2

	
>>> vars(f)
{}
>>> f.y = 42
>>> vars(f)
{'y': 42}

As soon as you assign a new attribute y to the function object, it becomes available in the dictionary returned by the vars() function. However, the local variable x is not an attribute of f, so it is not part of the returned dictionary.

[How to Fix] TypeError: vars() argument must have __dict__ attribute

If you pass an argument into the vars() function that doesn’t have a __dict__() function, Python raises a TypeError. This means that the object in question doesn’t have any attributes such as an integer, float, list, etc.

>>> vars(42)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    vars(42)
TypeError: vars() argument must have __dict__ attribute

You can fix it by only passing arguments that have overwritten the __dict__ method such as a function or a custom object:

>>> def f():
	return 42

>>> vars(f)
{}
>>> f.val = 'YES'
>>> vars(f)
{'val': 'YES'}

Summary

Python’s built-in vars() function returns a dictionary of name: value mappings of all the names defined in the local scope or the scope of the optional object argument, and their associated values.

When used without an argument, vars() returns the same as locals() that returns a dictionary of name --> object mappings of names defined in the current local scope and objects being their associated values.

>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> vars() == locals()
True

When used with an object argument, vars(object) returns the same as object.__dict__() that returns a dictionary of name --> object mappings of writable names defined in the object’s scope and objects being their associated values.

>>> def f():
	x = 2

	
>>> vars(f)
{}
>>> f.y = 42
>>> vars(f)
{'y': 42}

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!