Python: splitting a function and arguments

喜欢而已 提交于 2020-01-17 01:30:28

问题


Here are some simple function calls in python:

foo(arg1, arg2, arg3)
func1()

Assume it is a valid function call.

Suppose I read these lines while parsing a file.

What is the cleanest way to separate the function name and the args into a list with two elements, the first a string for the function name, and the second a string for the arguments?

Desired results:

["foo", "arg, arg2, arg3"]
["func1", ""]

I'm currently using string searches to find the first instance of "(" from the left side and the first instance of ")" from the right side and just splicing the string with those given indices, but I don't like how I am approaching the problem.


回答1:


I'm currently doing something similar using regular expressions. Adapting my code to your case, the following works with the examples you provide.

import re

def explode(s):
    pattern = r'(\w[\w\d_]*)\((.*)\)$'
    match = re.match(pattern, s)
    if match:
        return list(match.groups())
    else:
        return []



回答2:


If you're parsing a Python file in Python, consider using Python's parser: ast (specifically the ast.parse() call).

That said, your current approach isn't terrible (though it will break on function calls that spam multiple lines). There are few completely correct approaches short of the aforementioned full parser - for instance, you could count matching parens, so that a((b,c)) would return the correct value even if there was a line break in the middle - but then that code would probably do the wrong thing when faced with a((b, "c)")), and so on.



来源:https://stackoverflow.com/questions/9645061/python-splitting-a-function-and-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!