When introspecting a #Python object, I sometimes use a comprehension to remove dunder method noise from dir(...) output:

>>> numbers = [2, 1, 3]
>>> public = [name for name in dir(numbers) if not name.startswith("_")]
>>> public
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

This removes MANY underscore-prefixed methods:

>>> len(dir(numbers)) - len(public)
37

Anyone know if something like dir(..., public=True) has ever been proposed?

Found this previous discussion that didn't go anywhere:
https://discuss.python.org/t/add-a-flag-hide-magic-names-in-dir/7276

Maybe worth revisiting?

Some counter-arguments I imagine would crop up:
1. what comes back from __dir__ should be up to the object and Python shouldn't customize it at all
2. assuming that an underscore prefix has special meaning may be inaccurate. As an example, there's a "public" _astuple() method on namedtuples.
3. It's ambiguous. Why check for one underscore instead of 2? And are unofficial dunders removed?

Add a flag "hide magic names" in dir

Hi. 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 🙂 and I propose to change the signature to dir([object], *, show_dunder=True) Additionally (but I’m not sure about the back-com...

Discussions on Python.org