我认为创建匿名函数的困难有点让人头疼。您真正想要做的是将相关代码保持在一起,并使代码整齐。因此,我认为装饰师可能会为您工作。
import re
# List of pairs (regexp, handler)
handlers = []
def handler_for(regexp):
"""Declare a function as handler for a regular expression."""
def gethandler(f):
handlers.append((re.compile(regexp), f))
return f
return gethandler
@handler_for(r'^<\w+> (.*)')
def handle_message(msg):
print msg
@handler_for(r'^\*{3} (.*)')
def handle_warning(msg):
global num_warnings, num_fatals
num_warnings += 1
if is_fatal(msg):
num_fatals += 1