9.7. Idiom Vars
vars([object])
Without arguments, equivalent to
locals()
With an argument, equivalent to
object.__dict__
9.7.1. SetUp
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def login(self):
... return 'logged-in'
...
... def logout(self):
... return 'logged-out'
9.7.2. Class
>>> vars(User)
mappingproxy({
'__module__': '__main__',
'__firstlineno__': 1,
'__init__': <function User.__init__ at 0x...>,
'login': <function User.login at 0x...>,
'logout': <function User.logout at 0x...>,
'__static_attributes__': ('firstname', 'lastname'),
'__dict__': <attribute '__dict__' of 'User' objects>,
'__weakref__': <attribute '__weakref__' of 'User' objects>,
'__doc__': None})
9.7.3. Instance
>>> alice = User('Alice', 'Apricot')
>>>
>>> vars(alice)
{'firstname': 'Alice', 'lastname': 'Apricot'}
9.7.4. Vars vs __dict__
The same
Function
vars()
use__dict__
for the resultUsing
vars()
is preferred
>>> alice = User('Alice', 'Apricot')
>>>
>>> vars(alice)
{'firstname': 'Alice', 'lastname': 'Apricot'}
>>>
>>> alice.__dict__
{'firstname': 'Alice', 'lastname': 'Apricot'}
9.7.5. Usage
keys
values
>>> keys = list(vars(alice).keys())
>>> values = list(vars(alice).values())
>>>
>>> print(keys)
['firstname', 'lastname']
>>>
>>> print(values)
['Alice', 'Apricot']
9.7.6. Assignments
# %% About
# - Name: Idiom Vars Object
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Get state of `alice` object (all attributes and values in dict format)
# 2. Define `result: dict` with the result
# 3. Run doctests - all must succeed
# %% Polish
# 1. Pobierz stan obiektu `alice` (wszystkie atrybuty i wartości w formacie dict)
# 2. Zdefiniuj `result: dict` z wynikiem
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# {'username': 'alice', 'password': 'secret', 'authenticated': False}
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert isinstance(alice, User)
>>> assert hasattr(alice, 'username')
>>> assert hasattr(alice, 'password')
>>> assert hasattr(alice, 'authenticated')
>>> assert getattr(alice, 'username') == 'alice'
>>> assert getattr(alice, 'password') == 'secret'
>>> assert getattr(alice, 'authenticated') is False
>>> assert type(result) is dict
>>> assert len(result) == 3
>>> assert 'username' in result
>>> assert 'password' in result
>>> assert 'authenticated' in result
>>> result
{'username': 'alice', 'password': 'secret', 'authenticated': False}
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: dict[str, str|bool]
# %% Data
class User:
def __init__(self, username, password):
self.username = username
self.password = password
self.authenticated = False
def login(self):
self.authenticated = True
def logout(self):
self.authenticated = False
alice = User('alice', 'secret')
# %% Result
result = ...
# %% About
# - Name: Idiom Vars Class
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Get state of `User` class (all attributes and values in dict format)
# 2. Define `result: dict` with the result
# 3. Run doctests - all must succeed
# %% Polish
# 1. Pobierz stan klasy `User` (wszystkie atrybuty i wartości w formacie dict)
# 2. Zdefiniuj `result: dict` z wynikiem
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# mappingproxy({'__dict__': <attribute '__dict__' of 'User' objects>,
# '__doc__': None,
# '__firstlineno__': 67,
# '__init__': <function User.__init__ at 0x...>,
# '__module__': '...',
# '__static_attributes__': ('authenticated', 'password', 'username'),
# '__weakref__': <attribute '__weakref__' of 'User' objects>,
# 'login': <function User.login at 0x...>,
# 'logout': <function User.logout at 0x...>})
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> from inspect import isclass
>>> assert isclass(User)
>>> assert '__init__' in result
>>> assert 'login' in result
>>> assert 'logout' in result
>>> pprint(result, width=120) # doctest: +ELLIPSIS
mappingproxy({'__dict__': <attribute '__dict__' of 'User' objects>,
'__doc__': None,
'__firstlineno__': ...,
'__init__': <function User.__init__ at 0x...>,
'__module__': '...',
'__static_attributes__': ('authenticated', 'password', 'username'),
'__weakref__': <attribute '__weakref__' of 'User' objects>,
'login': <function User.login at 0x...>,
'logout': <function User.logout at 0x...>})
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: dict[str, str|bool]
# %% Data
class User:
def __init__(self, username, password):
self.username = username
self.password = password
self.authenticated = False
def login(self):
self.authenticated = True
def logout(self):
self.authenticated = False
# %% Result
result = ...