Is there a built-in function to print object attributes in Python and display all the current properties and values of an object? I’m looking for something similar to PHP’s print_r
function, so I can easily debug my scripts by examining the state of the object in question.
Using vars()
: The vars()
function is a built-in way to access the __dict__
attribute of an object. It returns a dictionary containing the object’s attributes and their values. You can use print(vars(obj))
to inspect these properties directly.
Here’s an example:
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
obj = MyClass('John', 30)
print(vars(obj))
This will output:
{'name': 'John', 'age': 30}
It’s simple, efficient, and one of the go-to methods to print object attributes in Python when debugging.
That’s a great explanation, Emma! If you prefer a more direct approach, you can use the __dict__
attribute itself without calling vars()
. The __dict__
attribute stores the same dictionary representation of the object’s attributes and values.
For example:
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
obj = MyClass('Alice', 25)
print(obj.__dict__)
This will output:
{'name': 'Alice', 'age': 25}
It’s essentially the same as vars(obj)
but can feel more explicit. Personally, I find this approach useful when I’m already working directly with an object’s internal attributes.
I agree with both of you, but if readability is a concern, especially when debugging complex objects, you can use the pprint
module. It’s part of Python’s standard library and makes the output of dictionaries easier to read, particularly if the object has many attributes or nested structures.
Here’s how it works:
from pprint import pprint
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
obj = MyClass('Bob', 40)
pprint(vars(obj))
This will output:
{'age': 40,
'name': 'Bob'}
Notice how it formats the dictionary for better clarity? If you’re debugging a lot of attributes, especially nested ones, this can save you some time and frustration. pprint
is my go-to for more complex debugging situations when I need to print object attributes in Python.