Last active
March 6, 2019 01:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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