[Python-ideas] dir with a glob?

Steven D'Aprano steve at pearwood.info
Thu Jun 30 18:31:38 CEST 2011

Ben Finney wrote:
> Sturla Molden <sturla at molden.no> writes:
>> dir(object, "foo*")
> I ask again: what would you expect (give an example) the output of this
> to be?

That specific example should return an empty list, since object has no 
attributes that match the glob foo*

>> What I am asking is if the need to filter the output from dir is so
>> common that it could warrant a change to Python?
> Given that we already have ways to filter a sequence built into the
> language, I doubt the need for a special way to filter the output from
> some particular function.

There is precedence though.

Many string methods have special way to limit their output to some 
subset of results, rather than relying on a generic, built-in way to do 
the same thing:

mystr.find("spam", 23, 42) vs mystr[23:42].find("spam")

dir itself already duplicates functionality available elsewhere:

 >>> dir() == sorted(globals())

dir with an argument is a little trickier, but it's not far off a one-liner:

dir(d) == sorted(
   set(sum((o.__dict__.keys() for o in ((d,)+type(d).__mro__)), []))

(at least for new-style objects with no __slots__).

dir is a convenience function, designed for interactive use. The docs 
make it explicit:

Because dir() is supplied primarily as a convenience for use at an 
interactive prompt, it tries to supply an interesting set of names more 
than it tries to supply a rigorously or consistently defined set of names...


Given that, I see no downside to making dir more convenient for 
interactive use. That's what it's for.


More information about the Python-ideas mailing list