Welcome, guest | Sign In | My Account | Store | Cart

dir() is useful for interactively exploring the attributes and methods of objects at the command line. But sometimes dir() returns a lot of information:

>>> len(dir(decimal.Decimal))  # too much information!
137

It can be helpful to filter the list of names returned. This enhanced version of dir does exactly that, using simple string globbing:

>>> dir(decimal.Decimal, '*log*')  # just attributes with "log" in the name
['_fill_logical', '_islogical', '_log10_exp_bound', 'log10', 'logb', 
'logical_and', 'logical_invert', 'logical_or', 'logical_xor']
Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import sys
_dir = dir
_sentinel = object()

def dir(obj=_sentinel, glob=None):
    from fnmatch import fnmatchcase
    if obj is _sentinel:
        # Get the locals of the caller, not our locals.
        names = sorted(sys._getframe(1).f_locals)
    else:
        names = _dir(obj)
    if glob is None: return names
    return [name for name in names if fnmatchcase(name, glob)]

This enhanced dir() uses the fnmatch module for globbing, so it accepts whatever globbing meta-characters fnmatch understands:

*        one or more characters
?        a single character
[seq]    matches any char in seq
[!seq]   matches any char not in seq

One subtlety is that the built-in dir() with no arguments returns names in the local scope. This uses sys._getframe to look outside of the custom dir() function and get the locals of the caller, but be warned that not all implementations of Python have _getframe available:

http://docs.python.org/library/sys.html#sys._getframe http://bugs.python.org/issue6712

2 comments

Ed 12 years, 10 months ago  # | flag

For a version with a few more bells and whistles, I'd recommend checking out "see"

https://github.com/inky/see

Eric Snow 12 years, 9 months ago  # | flag

Could sys._getframe(1) be replaced with inspect.stack()[1][0]?

Sweet recipe by the way. Nice and easy.