Skip to content

Instantly share code, notes, and snippets.

@sebastiancarlos
Last active August 8, 2024 04:17
Show Gist options
  • Save sebastiancarlos/6be577452f639a9c0a9c81aa78189147 to your computer and use it in GitHub Desktop.
Save sebastiancarlos/6be577452f639a9c0a9c81aa78189147 to your computer and use it in GitHub Desktop.
Like dir(), but filters out __*__ attributes, standard library packages, and built-ins, to give a better idea of the object's custom attributes.
# explicitly define the interface
__all__ = ["minimal_dir"]
from functools import cache
@cache
def get_stdlib_packages():
""" Get list that should include all stdlib package/module names.
Not perfect. Has false positives.
"""
import os
result = []
stdlib_dir = os.path.dirname(os.__file__)
for file in os.listdir(stdlib_dir):
# first, add all directories in stdlib_dir, except for 'site-packages'
if os.path.isdir(os.path.join(stdlib_dir, file)) and file != "site-packages":
result.append(file)
# then, add all .py files in stdlib_dir, but without the extension
if file.endswith(".py"):
result.append(file[:-3])
return result
def minimal_dir(*args):
""" Like dir(), but minimal.
Filters out:
- __*__ attributes,
- stdlib packages,
- builtins.
Example:
>>> dir() # this module
[
'__all__',
'__builtins__',
... # ten more attributes
]
>>> minimal_dir() # now cleaner output
['get_stdlib_packages', 'minimal_dir']
"""
import re
import builtins
# If no arguments, we need to eval "dir()" on the previous stack to
# simulate running it there.
if len(args) == 0:
from inspect import currentframe
frame = currentframe().f_back
value = eval("dir()", frame.f_globals, frame.f_locals)
else:
value = dir(*args)
result = []
stdlib_packages = get_stdlib_packages()
for attr in value:
# ignore dunder attributes
if re.match("__.*__", attr):
continue
# ignore stdlib packages
if attr in stdlib_packages:
continue
# ignore builtins
if attr in dir(builtins):
continue
result.append(attr)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment