Skip to content

Instantly share code, notes, and snippets.

@CH-DanReif
Last active March 6, 2019 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CH-DanReif/260122572fa6cae32a9b816fcfb61de9 to your computer and use it in GitHub Desktop.
Save CH-DanReif/260122572fa6cae32a9b816fcfb61de9 to your computer and use it in GitHub Desktop.
WTAF: Try to grok an arbitrary Python object, as well as one reasonably can. N.b. it tries to call the methods. You own anything you break.
import types
from typing import Callable, Dict
def _funcify(obj: object, key: str, hist: Dict) -> str:
"""
Call {obj}.{key}() if possible.
@param hist: A dict that starts empty when we begin enumerating an object.
If this method would otherwise recurse, even in a loop, don't.
"""
this_key = getattr(obj, key)
if key in hist:
return f'<recursive {type(this_key).__name__} {key}({getattr(this_key, "__text_signature__", "?")})>'
hist[key] = 1
try:
return repr(this_key())
except Exception:
return f'<{type(this_key).__name__} {key}({getattr(this_key, "__text_signature__", "?")})>'
def explain(obj: object) -> Dict[str, str]:
hist = {}
return {
k
if not isinstance(getattr(obj, k, None), Callable)
else f"{k}()": getattr(obj, k, None)
if not isinstance((getattr(obj, k, None)), Callable)
else _funcify(obj, k, hist)
for k in dir(obj)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment