使用正则表达式检测python函数?

app*_*der 0 python regex

我想在python脚本中提取所有python函数.有没有我可以使用的单一正则表达式,例如:

import re
all_functions = re.findall(regex, python_script)
Run Code Online (Sandbox Code Playgroud)

我已经实现了一个非常麻烦的方法,涉及许多if语句,但我觉得有一个更优雅的解决方案与正则表达式.

我认为正则表达式应该是这样的:

'def.*?\n\S'
Run Code Online (Sandbox Code Playgroud)

因为:

  1. 功能始于 def
  2. 随后都有(但我们想要非贪婪)
  3. 在换行符后,函数结束\n,下一行的起始字符不是空格\S

但是,我似乎无法通过多行来实现这一点.

编辑:Python函数可能包含在没有.py扩展名的文件中; 例如,它们可以包含在具有.ipynb扩展名的IPython笔记本中,因此我不一定总是import代码和使用dir().

Mar*_*ers 8

不要使用正则表达式.让Python为您解析代码并找到ast模块的所有函数定义:

import ast

with open(python_sourcefile) as sourcefile:
    tree = ast.parse(sourcefile.read(), sourcefile.name)

for node in ast.walk(tree):
    if isinstance(node, ast.FunctionDef):
        print(node.name)
Run Code Online (Sandbox Code Playgroud)

如果代码包含在.ipynb文件中,则解析文件并提取code单元格,然后input通过相同的过程放置源代码.

使用ast模块源本身进行演示:

>>> import ast
>>> with open(ast.__file__.rstrip('c')) as sourcefile:
...     tree = ast.parse(sourcefile.read(), sourcefile.name)
... 
>>> for node in ast.walk(tree):
...     if isinstance(node, ast.FunctionDef):
...         print(node.name)
... 
parse
literal_eval
dump
copy_location
fix_missing_locations
increment_lineno
iter_fields
iter_child_nodes
get_docstring
walk
_convert
_format
_fix
visit
generic_visit
generic_visit
Run Code Online (Sandbox Code Playgroud)