I love dir()
, I hate dir()
.
One of the first things I teach students, whether new or experienced programmers, is the triad of built in functions critical for figuring things out in Python:
type()
dir()
help()
Of these, dir()
is the function I use more than any other, whether in class or while doing my own programming. It's absolutely critical. And yet it annoys the hell out of me.
dir is short for directory, and provides a list of all the names associated with an object in Python, which are the attributes and methods you can use with that object.
Here's the output of dir()
when called on list
, one of the early objects I talk about in class:
print(dir(int))
What's wrong with that for students? Let me count the ways...
Eventually I got tired of spending several minutes explaining all these problems to students, and over the years I developed my own version of dir()
to address the issues. Seeing me use it, students started asking if they could use it in their own coding. To my surprise, I started finding myself using it when doing development, and I found myself discovering things about objects that I'd never noticed before.
Here's the output of mydir()
for a list
:
from mydir import mydir
mydir(list)
Which do you prefer?
This makes things so much nicer for students (and for their instructors...)
If you want to see the private (underscored) items, you can do so:
mydir(list, private=True)
Notice that classes and attributes are separated out from methods.
If you'd like to make use of this, you can get it from github (I may submit it to pypi as a module in the future):
I intend to make some additions:
Suggestions and patches welcome!