[Python-ideas] dir with a glob?

Georg Brandl g.brandl at gmx.net
Thu Jun 30 19:22:39 CEST 2011

On 30.06.2011 18:31, Steven D'Aprano wrote:
> 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())
> True
> 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__).

And don't forget about __dir__...

> dir is a convenience function, designed for interactive use. The docs 
> make it explicit:
> [quote]
> 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...
> http://docs.python.org/library/functions.html#dir
> Given that, I see no downside to making dir more convenient for 
> interactive use. That's what it's for.

I agree.  I often am looking for a specific member that I know exists, but
don't recall the exact name (and in particular, not what the name starts
with: at least dir() output is sorted).  Searching through one screenful
of members isn't pretty.

So, +1 for the second argument.


More information about the Python-ideas mailing list