mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-25 09:11:32 +00:00
Create helper methods for parsing source code
This commit is contained in:
parent
327376232d
commit
b1159d6c3e
26
lib/source_code.py
Normal file
26
lib/source_code.py
Normal file
@ -0,0 +1,26 @@
|
||||
import ast
|
||||
import inspect
|
||||
import re
|
||||
from io import StringIO
|
||||
|
||||
|
||||
def find_local_variable_value(func, local_variable_name):
|
||||
func_src = inspect.getsource(func)
|
||||
func_ast = ast.parse(func_src)
|
||||
for node in ast.walk(func_ast):
|
||||
if isinstance(node, ast.Assign):
|
||||
for target in node.targets:
|
||||
if isinstance(target, ast.Name):
|
||||
if target.id == local_variable_name:
|
||||
return node.value.s
|
||||
|
||||
|
||||
def get_source_code(func, strip_comments=False):
|
||||
source = inspect.getsource(func)
|
||||
if strip_comments:
|
||||
# TODO: less fragile way to do this (tokenizer sadly inserts whitespaces all around)
|
||||
comment_pattern = re.compile('^(\s.*)#.*$')
|
||||
source = ''.join((
|
||||
line for line in StringIO(source).readlines() if re.match(comment_pattern, line) is None
|
||||
))
|
||||
return source
|
Loading…
Reference in New Issue
Block a user