Python Friday #26: The dir() Function

I constantly run into the problem that I cannot remember what methods exist on an object. If you have the same problem in the interactive prompt, then the built-in function dir() can help you.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

How to use dir()

You can use the dir() function without any argument. In this case it looks at your local scope and returns what it finds there:

The output changes depending on what exists in your scope. If you create a list called numbers, dir() will find them:

A much more common use case is to pass an object as an argument to dir(). In this case dir() tries to return an interesting set of names that may help you. Keep in mind that this means you may not get every method and attribute of that object.

The output helps you to figure out what you can do with the object. You may call the built-in function help() to read the docstring about the interesting names or directly try to call the method on your object:

 

Conclusion

I find the dir() method a great help when I play with libraries in the Python Interpreter – especially when the documentation does not cover all attributes. In this case I can look at the output without the need to dive into the source code. I hope this will help you as well.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.