Print all properties of a Python Class
To output all properties of a Python class instance, use vars()
or __dict__
. Here's an example:
This will print:
prop1 = value1
prop2 = value2
In this case, vars(obj)
or obj.__dict__
both convert the object's properties into a dictionary format, thus enabling you to print them easily.
Developing further: Complex classes
For more complex classes featuring methods, static variables etc., you might want to leave these out from the printed properties. Use dir()
along with a list comprehension to achieve that:
Here we're filtering out methods and 'magic' attributes, that include double underscores, to give a cleaner property list.
Persistent storage: Shelve it!
For storing class properties persistently, Python's shelve
module comes handy. It allows you to store the class instances directly, no need for manual dictionary conversion:
Ppretty please: Printing with style
ppretty
is a third-party library that promises (and delivers!) beautifully formatted printouts:
This comes in handy when debugging or in need of a user-friendly representation of an object's properties.
Hidden attributes: Pulling back the curtain
Classes with custom getter/setter methods won't expose their attributes via __dict__
. Here, implementing a custom method is the way to go:
This goes straight to the properties via their public interface, avoiding any unwanted attention to the underlying data.
Handling the big guns: Scalability
When the classes have a large number of attributes, decorators or metaprogramming techniques can help avoid the manual labor:
The auto_repr
decorator appends a custom string representation method, that automatically lists all properties, to any class it gets applied to.
Was this article helpful?