Set a flag on the function or a global?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jun 16 18:46:03 EDT 2015


On Tue, 16 Jun 2015 13:45:01 +0100, Oscar Benjamin wrote:

> On 16 June 2015 at 09:18, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>>
>> The primary use-case (at least *my* use-case, and hopefully others) is
>> to have "from module import edir as dir" in their Python startup file.
>> That means that when running interactively, they will get the enhanced
>> version of dir, but when running a script or an application they'll
>> just get the regular one.
>>
>> (Ideally, the regular one will eventually gain the same superpowers as
>> edir has, but that's a discussion for another day.)
>>
>> Besides, apart from the inspect module, which probably shouldn't, who
>> uses dir() programmatically?
>>
>> (If you do, you'll be glad to hear that edir() behaves the same as
>> regular dir() by default.)
> 
> What's the point in giving edir two modes if one of them is the same as
> dir? You could just do "from module import edir" and then use dir/edir
> as desired.

Oh ye of little faith :-)

I practically live in the Python interactive interpreter, and this has 
evolved from functionality I have wished dir has. It's a lot more than 
just whether or not dunders are displayed by default.

The most important feature of edir() is that it supports globbing and 
substring matches:


py> dir("", "low")
['islower', 'lower']
py> dir('', '*er')
['center', 'isidentifier', 'islower', 'isupper', 'lower', 'upper']


By default, globs are case-insensitive, but you can force them to be case-
sensitive with a metachar. I added this because I kept coming across 
classes with methods that used CamelCase when I expected lowercase. It 
understands the standard metacharacters ? * and [] as well as prefixes ! 
to invert the match and = to force case-sensitivity.

It also optionally includes the metaclass of the object. This was 
requested by somebody else as standard behaviour for dir, on python-ideas 
and the bug tracker, but rejected.

The reason this was requested is that dir() intentionally doesn't return 
all the attributes visible from an object:

py> "mro" in dir(str)
False
py> str.mro
<built-in method mro of type object at 0x81db360>


I thought it seemed like an interesting idea, and added it as an option 
with a keyword-only argument:

py> "mro" in dir(str, meta=True)
True


but frankly I'm not entirely sure this feature is useful. Time will tell.


> Personally I just use ipython's tab-completion instead of dir. It shows
> the dunders if you first type underscores but hides them otherwise e.g.:

Tab completion is great, but it solves a different problem. One with some 
overlap, admittedly, but still different.


-- 
Steven D'Aprano



More information about the Python-list mailing list