Add a flag "hide magic names" in dir

While I understand the current behavior of dir(), most of the time I use it is to quickly have a glance of the “normal” exposed names.
I would propose to add a keyword-only, default-is-current behavior, flag to allow the caller to show only the “normal” names (i.e. - no dunder stuff).

For the name of the flag, I think this is the most complex thing :slight_smile: and I propose to change the signature to

dir([object], *, show_dunder=True)

Additionally (but I’m not sure about the back-compatibility…), also the __dir__() method should accept the same keyword-only flag.

What do you think about it?

1 Like

dir is a convenience function that most of the time delegates to the object’s __dir__ implementation (only performs an inspection if cannot find it).

There are several __dir__ implementations in Python’s code (modules, classes, other objects, …) and each one displays the most relevant information for an interactive context with different criteria, as do so many other __dir__ implementations in the vast Python ecosystem. Presuming the normality of an attribute on the basis of underscores sounds kinda dunderphobic to me :sweat_smile: Sorry, just kidding. What I mean is that since dunders are only a convention (except in the case of name mangling), often it would be difficult to know what kind of information is being hidden.

IMO this is a case that fits perfectly with the purpose of PYTHONSTARTUP. I usually have a very small wrapper over dir() in mine to identify methods at a glance and I found it very convenient. Adapted to your idea, would be something like this:

def ddir(obj):
    return [a + '()' if callable(getattr(obj, a)) else a
            for a in dir(obj) if not (a[:2] == '__' == a[-2:])]