関数定義をインポートできる場合は、walk ASTを使用するか、inspectを使用します。
署名の横に解析する必要がある場合は、pyparsingまたはfuncparselibと考えてください。
まだ正規表現を使用する必要がある場合は、私に同行してください。
import re
# Python identifiers start with a letter or _,
#and continue with these or digits.
IDENT = '[A-Za-z_][A-Za-z_0-9]*'
# Commas between identifiers can have any amout of space on either side.
COMMA = '\s*,\s*'
# Parameter list can contain some positional parameters.
# For simplicity we ignore now named parameters, *args, and **kwargs.
# We catch the entire list.
PARAM_LIST = '\((' + IDENT+'?' + '(?:' + COMMA+IDENT + ')*'+ ')?\)'
# Definition starts with 'def', then identifier, some space, and param list.
DEF = 'def\s+(' + IDENT + ')\s*' + PARAM_LIST
ident_rx = re.compile(IDENT)
def_rx = re.compile(DEF)
def test(s):
match = def_rx.match(s)
if match:
name, paramlist = match.groups()
# extract individual params
params = [x.group() for x in ident_rx.finditer(paramlist or '')]
print s, name, params
else:
print s, 'does not match'
test('def foo(a, b)')
test('def foo()')
test('def foo(a,b,c , d, e)')
test('deff foo()')
test('def foo(a, 2b)')
上記のコードは、デフォルト値、*args
または**kwargs
、または末尾のカンマでパラメータを処理できないことに注意してください、Pythonの2の法的def foo(a, (b, c))
このすべてのようなおろかなものを追加することができますが、複雑さが急上昇します。
あなたのケースがかなり単純でない限り(上のコード例は境界線です)、上のパーサーリンクを参照してください。
正規表現はパーサーではありません。 –
[ASTを歩く](http://docs.python.org/dev/library/ast.html)はなぜですか? –
末尾のカンマは実際にはPythonによって許可されています。 – 9000