When introspecting a #Python object, I sometimes use a comprehension to remove dunder method noise from dir(...) output:
-
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)
37Anyone know if something like dir(..., public=True) has ever beet proposed?
-
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)
37Anyone know if something like dir(..., public=True) has ever beet proposed?
Found this previous discussion that didn't go anywhere:
https://discuss.python.org/t/add-a-flag-hide-magic-names-in-dir/7276Maybe 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? -
R relay@relay.publicsquare.global shared this topic