Created
May 30, 2013 02:44
-
-
Save Ceasar/5675442 to your computer and use it in GitHub Desktop.
Works limitedly.
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 inspect | |
import re | |
import pprint | |
FUNCTION_PATTERN = re.compile(".*\s((\.|\w)+)\(") | |
def has_function_token(token): | |
return FUNCTION_PATTERN.match(token) is not None | |
def get_function_name(token): | |
return FUNCTION_PATTERN.match(token).group(1) | |
def get_function_by_name(func_name, context=None): | |
try: | |
head, tail = func_name.split('.', 1) | |
except ValueError: | |
if context is None: | |
try: | |
return globals()[func_name] | |
except KeyError: | |
# could be a builtin | |
return getattr(__builtins__, func_name) | |
else: | |
return getattr(context, func_name) | |
else: | |
if context is None: | |
try: | |
return get_function_by_name(tail, globals()[head]) | |
except KeyError: | |
# could be a builtin | |
return get_function_by_name(tail, getattr(__builtins__, head)) | |
else: | |
return get_function_by_name(tail, | |
getattr(context, head)) | |
def gen_functions_used(func): | |
lines = inspect.getsource(func).split('\n') | |
return (get_function_name(line) for line in lines[1:] | |
if has_function_token(line)) | |
def is_terminal(function_name): | |
return "." in function_name or hasattr(__builtins__, function_name) | |
def get_first_principles(func): | |
graph = {} | |
for function_name in gen_functions_used(func): | |
print func.__name__, function_name | |
if function_name in graph: | |
continue | |
elif is_terminal(function_name) or function_name == func.__name__: | |
graph[function_name] = {} | |
else: | |
assert function_name != 'get_first_principles' | |
func = get_function_by_name(function_name) | |
graph[function_name] = get_first_principles(func) | |
return graph | |
pprint.pprint(get_first_principles(get_function_by_name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment