Last active
June 12, 2019 10:59
-
-
Save jnpn/e1c0782ecbb3063c0506a578c454ba9c to your computer and use it in GitHub Desktop.
Some reflection helpers
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
""" | |
Reflection utils for repl interaction | |
""" | |
import types | |
from collections.abc import Iterable | |
from itertools import groupby | |
def kinds(m): | |
""" | |
Classifies fields according to their name/syntax | |
""" | |
if m.istitle(): | |
return 'Class' | |
elif m.startswith('__'): | |
if m.endswith('__'): | |
return 'protocol' | |
else: | |
return 'private' | |
else: | |
return 'public' | |
##################################################################### PREDICATES | |
def isgen(o): | |
return type(o) is types.GeneratorType | |
def isiter(o): | |
return isinstance(o, Iterable) | |
def degenerate(o): | |
""" | |
Transforms collections of iterators/generators into | |
collections of eager types. | |
@status: alpha | |
""" | |
k = type(o) | |
if k is dict: | |
def epair(k,v): | |
ek = degenerate(k) | |
ev = degenerate(v) | |
return ek,ev | |
return list(epair(k,v) for k,v in o.items()) | |
elif k is list: | |
return [degenerate(s) for s in o] | |
elif k is set: | |
return set([degenerate(s) for s in o]) | |
elif isgen(o): | |
return list(o) + ['gen'] | |
elif isiter(o) and not k is str: # don't turn strings into list of chars | |
# BUG HERE | |
return [degenerate(e) for e in iter(o)] # list(o) + [('iter',o)] | |
else: | |
# atomic type | |
return o | |
##################################################################### REFLECTION | |
def ref(o): | |
for g,ks in groupby(dir(o), kinds): | |
yield g, sorted(list(ks)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment