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']
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:
For a version with a few more bells and whistles, I'd recommend checking out "see"
Could sys._getframe(1) be replaced with inspect.stack()?
Sweet recipe by the way. Nice and easy.