How to Show All Properties of an Object in Python

When printing an object in Python it will tell you that it is of the data type object and nothing else. This isn't particularly useful if you are working with an object you know little about and would like to be able to quickly see what is actually inside it.

 

I often have this issue with objects created by Python packages – sure I could go and look the package documentation, but wouldn't it be easier to just show the properties of an object from within Python? It turns out there are a couple of ways to easily achieve this.

 

Using vars() and pprint

the Python vars() function will return all the properties of any object (the __dic__ attributes). The output from vars() will be minified, to fix that import the pprint package and use it to pretty-print the result.

 

from pprint import pprint

pprint(vars(my_object))

 

Using dir()

The same thing as above can be done with the dir() function, except it will provide a much cleaner output containing an array of all the properties. Let's try this on a response object returned from the requests.get() method.

 

import requests
from pprint import pprint

url = 'https://www.skillsugar.com/media/image/parse-json-in-python-1600457348.png'

img = requests.get(url)

pprint(dir(img))
['__attrs__',
 '__bool__',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__enter__',
 '__eq__',
 '__exit__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__nonzero__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_content',
 '_content_consumed',
 '_next',
 'apparent_encoding',
 'close',
 'connection',
 'content',
 'cookies',
 'elapsed',
 'encoding',
 'headers',
 'history',
 'is_permanent_redirect',
 'is_redirect',
 'iter_content',
 'iter_lines',
 'json',
 'links',
 'next',
 'ok',
 'raise_for_status',
 'raw',
 'reason',
 'request',
 'status_code',
 'text',
 'url']

 

The values towards the bottom of the output list are all the properties available on the object returned from requests.get(). One import thing to watch out for is that it doesn't differentiate between properties containing string values and methods. For example, json in the above list is actually a method but there is no indication of it.

 

Using the help() Function

The help() function will return the help documentation for a whole Python package or objects created from a package, depending on how you apply it.

 

print(help(my_object))

 

Conclusion

The three approaches above should make it easy to show all of the available properties on an object in Python. using dir() is probably the most useful as it is the easiest to read.

object property