Enhanced dir() function
steve+comp.lang.python at pearwood.info
Fri Jul 1 20:32:44 CEST 2011
Tim Chase wrote:
> On 06/30/2011 11:29 PM, Steven D'Aprano wrote:
>> The dir() function is designed for interactive use, inspecting objects
>> for the names of attributes and methods.
>> Here is an enhanced version that allows you to pass a glob to filter the
>> names you see:
>> Comments and improvements welcome.
> Having not seen any other comments on it fly by, I thought I'd
> respond. While in general I like the idea, I'm not sure when I'd
> go to the effort of bringing the function into my namespace when
> I could just do something like
> >>> [s for s in dir(...) if test_of_interest(s)]
If test_of_interest is complex, then the list comp is the better solution.
Globbing dir is intended for simple globs (naturally!), not complex filter
functions of arbitrary complexity. The equivalent is globbing in the shell:
[steve at sylar python]$ dir p*.py
parallel_map.py partition.py perms.py proc.py pyprimes.py
paragraphs.py peekable.py pi.py progress.py
> If it came in as an effortless (i.e. O(1) where I do it once and
> never again; not an O(n) where n=the number of times I invoke
> Python) default replacement for dir(), I'd reach for it a lot
> more readily. I seem to recall there's some environment-var or
> magic file-name that gets sourced on every startup.
There is some talk on the python-ideas mailing list about enhancing the
But in the meantime, you can add it to your site.py module, or better still,
use your own personal startup file rather than the system site.py. I have
an environment variable set in my .bashrc file:
and then put code I want to run at startup in startup.py. For Windows users,
I don't know how to set environment variables, but I dare say it would be
something similar: set the environment variable PYTHONSTARTUP to a file
name, and put the code in that file.
> I use the list-comp version on a regular basis:
> # implementation of which magic methods?
> [s for s in dir(foo) if s.startswith('__') and s.endswith('__')]
This would become:
> # ignore magic methods
> [s for s in dir(foo) if not (s.startswith('__') and
although strictly speaking, my version only tests for one leading and
trailing underscore, not two.
> # constants
> [s for s in dir(foo) if s.isupper()]
That's beyond the capabilities of simple globbing.
> # keywording
> [s for s in dir(foo) if 'bar' in s.lower()]
I'm of two minds about case-insensitive globbing. It could be done with a
slight change to the function, but I'm not sure if I want to.
> Anyways, even if it just includes a brief blurb about "and this
> is how you get it automatically in every Python session" (or a
> link to the docs on how to do that), it would raise it from "meh"
> to "nifty".
Thanks for the feedback.
More information about the Python-list