It seems like what you really want to do is parse the abstract syntax tree of the python file using the ast module . There are much better ways to do this than using regular expressions. Here is an example:
import ast
class FunctionVisitor(ast.NodeVisitor):
def __init__(self):
self.second_arg_names = []
def visit_FunctionDef(self, func):
"""collect function names and the second argument of functions that
have two or more arguments"""
args = func.args.args
if len(args) > 1:
self.second_arg_names.append((func.name, args[1].id))
self.generic_visit(func)
def find_func_args(filename=__file__):
"""defaults to looking at this file"""
with open(filename) as f:
source = f.read()
tree = ast.parse(source)
visitor = FunctionVisitor()
visitor.visit(tree)
print visitor.second_arg_names
assert visitor.second_arg_names == [("visit_FunctionDef", "func")]
if __name__ == "__main__":
find_func_args()
Dunes source
share