Bits N Bytes Banner

MAY 17 2021

Attribute Names dir()

Affiliate Link:

Get Method and Attribute Names with dir()

There is a nice little function in Python named “dir()”. One great feature of this function is that it can produce a list of attributes associated with an object. For example if you want to see the methods on the python pickle object you can do the following:

import pickle dir(pickle)

You can see in the output below all the associated attributes (ie - methods, etc.). This is a great little trick when you are deep in the weeds of your code and need a quick reference. You can also use it to test items to see if a specific method exists.

For example:

if “dump” in dir(pickle): print(“The dump method exists in this object.”)

This is extremely useful if you want to test a dynamic object to determine if a method, or attribute exists.