[英]Regex Pattern to find arguments passed into a function
For a project, I am trying to read through a python file and keep a list of all the variable being used within a certain function.对于一个项目,我正在尝试通读 python 文件并保留某个 function 中使用的所有变量的列表。 I am reading through the lines in the python file in string format and then focusing on a line where starting with "def".
我正在以字符串格式阅读 python 文件中的行,然后关注以“def”开头的行。 For the purpose of this example pretend we have the following line identified:
出于本示例的目的,假设我们已识别出以下行:
def func(int_var:int,float_var=12.1,string_var=foo()):
I want to use regex or any other method to grab the values within this function declaration.我想使用正则表达式或任何其他方法来获取此 function 声明中的值。
I want to grab the string "int_var:int,float_var=12.1,string_var=foo()"
, and later split it based on the commas to get ["int_var:int","float_var=12.1","string_var=foo()"]
我想获取字符串
"int_var:int,float_var=12.1,string_var=foo()"
,然后根据逗号拆分它以获得["int_var:int","float_var=12.1","string_var=foo()"]
I am having a lot of trouble being able to isolate the items between the parenthesis corresponding to 'func'.我在隔离与“func”相对应的括号之间的项目时遇到了很多麻烦。
Any help creating a regex pattern would be greatly appreciated!任何创建正则表达式模式的帮助将不胜感激!
Instead of regex, it is much easier and far more robust to use the ast
module:使用
ast
模块而不是正则表达式更容易且更健壮:
import ast
s = """
def func(int_var:int,float_var=12.1,string_var=foo()):
pass
"""
def form_sig(sig):
a = sig.args
d = [f'{ast.unparse(a.pop())}={ast.unparse(j)}' for j in sig.defaults[::-1]][::-1]
v_arg = [] if sig.vararg is None else [f'*{sig.vararg.arg}']
kwarg = [] if sig.vararg is None else [f'*{sig.kwark.arg}']
return [*map(ast.unparse, a), *d, *v_arg, *kwarg]
f = [{'name':i.name, 'sig':form_sig(i.args)} for i in ast.walk(ast.parse(s))
if isinstance(i, ast.FunctionDef)]
Output: Output:
[{'name': 'func', 'sig': ['int_var: int', 'float_var=12.1', 'string_var=foo()']}]
func_pattern = re.compile(r'^\s*def\s(?P<name>[A-z_][A-z0-9_]+)\((?P<args>.*)\):$')
match = func_pattern.match('def my_func(arg1, arg2):')
func_name = match.group('name') # my_func
func_args = match.group('args').split(',') # ['arg1', 'arg2']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.