Skip to content

Instantly share code, notes, and snippets.

@Ceasar
Created May 30, 2013 02:44
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 Ceasar/5675442 to your computer and use it in GitHub Desktop.
Save Ceasar/5675442 to your computer and use it in GitHub Desktop.
Works limitedly.
"""
"""
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