vars()is the lesser-known and arguably more Pythonic version of the
__dict__attribute (available on all classes that do not use
slots). From the docs:
Without an argument, act like locals().
With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), return that attribute.
As core Python contributor Raymond Hettinger points out on Twitter:
"Most folks prefer len(s) to s.__len__(), prefer next(it) to it.next(), but forget to use vars(s) rather than s.__dict__"
However, I think there's room to argue that
s.__dict__may be a little clearer than
vars(s). After all, (almost) everything in Python is an object, and very nearly all objects are backed by
>>> from timeit import timeit
Four million iterations later, we see that grabbing the
__dict__is over four and a half times faster. This should actually come as no surprise: accessing built-in functions (like
vars()/etc.) is always slower than object attribute access.