dir() / vars() / getattr()
| Since: | Python 2(2000) |
|---|
Built-in functions for dynamically inspecting, retrieving, and setting attributes and methods on objects. Useful for debugging and dynamic programming.
Syntax
dir(object) # Returns the __dict__ attribute of the object (a dictionary of attribute names and values). vars(object) # Retrieves the value of a named attribute from an object. getattr(object, name, default) # Sets the value of a named attribute on an object. setattr(object, name, value) # Checks whether an object has a named attribute. hasattr(object, name) # Deletes a named attribute from an object. delattr(object, name)
Function List
| Function | Description |
|---|---|
| dir(obj) | Returns a list of attribute names and method names of the object. Called without arguments, it returns a list of names in the current scope. |
| vars(obj) | Returns the object's __dict__. Lets you inspect an instance's attributes and their values as a dictionary. |
| getattr(obj, name, default) | Retrieves the value of an attribute specified by name as a string. Returns the default value if the attribute does not exist. |
| setattr(obj, name, value) | Sets the value of an attribute specified by name as a string. If the attribute does not exist, it is created. |
| hasattr(obj, name) | Returns True if the object has an attribute with the given name. |
| delattr(obj, name) | Deletes the attribute with the given name from the object. |
Sample Code
dir_vars_getattr.py
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}."
p = Person("Yagami Light", 17)
# Use dir() to inspect the attributes and methods of the object.
attrs = dir(p)
# Includes special methods like __init__ and __str__, as well as name, age, and greet.
# Filter out special methods starting with __ (dunder) before displaying.
public_attrs = [a for a in dir(p) if not a.startswith("_")]
print(public_attrs) # ['age', 'greet', 'name']
# Use vars() to get the instance's attributes as a dictionary.
print(vars(p)) # {'name': 'Yagami Light', 'age': 17}
# Use getattr() to retrieve an attribute value by name as a string.
attr_name = "name"
print(getattr(p, attr_name)) # Yagami Light
print(getattr(p, "height", "unknown")) # unknown (default value)
# You can also retrieve a method with getattr() and call it.
greet_method = getattr(p, "greet")
print(greet_method()) # Hello, I'm Yagami Light.
# Use setattr() to dynamically update an attribute value.
setattr(p, "age", 18)
print(p.age) # 18
# Dynamically add a new attribute.
setattr(p, "org", "To-Oh University")
print(p.org) # To-Oh University
# Use hasattr() to check whether an attribute exists before accessing it.
if hasattr(p, "email"):
print(p.email)
else:
print("No email address is registered.")
# Use delattr() to remove an attribute.
delattr(p, "org")
print(hasattr(p, "org")) # False
Running the code produces the following output:
python3 dir_vars_getattr.py
['age', 'greet', 'name']
{'name': 'Yagami Light', 'age': 17}
Yagami Light
unknown
Hello, I'm Yagami Light.
18
To-Oh University
No email address is registered.
False
Common Mistakes
Common Mistake 1: dir() May Include Attributes That Cannot Be Called Directly
dir() returns all attributes and methods in the inheritance chain. A name appearing in the result does not necessarily mean it can be called directly. Use hasattr() or getattr() to confirm existence.
class Investigator:
def __init__(self, name, org):
self.name = name
self.org = org
light = Investigator('Yagami Light', 'To-Oh University')
# dir() includes many special methods
attrs = [a for a in dir(light) if not a.startswith('_')]
print(attrs) # ['name', 'org'] (user-defined only)
# confirm existence with hasattr()
print(hasattr(light, 'name')) # True
print(hasattr(light, 'level')) # False
Common Mistake 2: Forgetting the Default Value in getattr() Causes AttributeError
getattr(obj, name) raises an AttributeError if the attribute does not exist. Providing a default value avoids the error.
class Investigator:
def __init__(self, name):
self.name = name
light = Investigator('Yagami Light')
# accessing a missing attribute raises AttributeError
try:
power = getattr(light, 'power') # AttributeError
except AttributeError as e:
print(f'No attribute: {e}')
The same logic can also be written as:
power = getattr(light, 'power', 0) # returns 0 (no error) print(power) # 0
Overview
These functions provide Python's reflection capabilities. Because attribute names can be specified dynamically as strings, they are useful in programs that manipulate object attributes based on configuration files or user input.
hasattr() internally calls getattr() and checks whether an exception is raised. If a property has side effects (such as database access or computation), simply calling hasattr() may trigger that logic. In such cases, wrapping the attribute access in a try-except block is safer.
The result of dir() includes inherited attributes and methods. To inspect only the attributes defined by the class itself, access the class's __dict__ directly with vars(ClassName). For type checking, see type() / isinstance().
If you find any errors or copyright issues, please contact us.