有没有可能把一个函数放在一个数据结构中,而不用先用def
给它命名
# This is the behaviour I want. Prints "hi".
def myprint(msg):
print msg
f_list = [ myprint ]
f_list[0]('hi')
# The word "myprint" is never used again. Why litter the namespace with it?
lambda函数的主体是严重受限的,所以我不能使用它们。
编辑:作为参考,这更像是我遇到问题的真实代码。
def handle_message( msg ):
print msg
def handle_warning( msg ):
global num_warnings, num_fatals
num_warnings += 1
if ( is_fatal( msg ) ):
num_fatals += 1
handlers = (
( re.compile( '^<\w+> (.*)' ), handle_message ),
( re.compile( '^\*{3} (.*)' ), handle_warning ),
)
# There are really 10 or so handlers, of similar length.
# The regexps are uncomfortably separated from the handler bodies,
# and the code is unnecessarily long.
for line in open( "log" ):
for ( regex, handler ) in handlers:
m = regex.search( line )
if ( m ): handler( m.group(1) )
发布于 2011-07-09 06:11:45
这是基于Udi's nice answer的。
我认为创建匿名函数的困难有点转移视线。你真正想做的是把相关的代码放在一起,并使代码整洁。所以我想装饰师可能会为你工作。
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
发布于 2011-07-09 05:28:20
解决实际问题的更好的干式方法:
def message(msg):
print msg
message.re = '^<\w+> (.*)'
def warning(msg):
global num_warnings, num_fatals
num_warnings += 1
if ( is_fatal( msg ) ):
num_fatals += 1
warning.re = '^\*{3} (.*)'
handlers = [(re.compile(x.re), x) for x in [
message,
warning,
foo,
bar,
baz,
]]
发布于 2011-07-09 21:30:37
继续使用模块化的自包含解决方案的Gareth's clean方法:
import re
# in util.py
class GenericLogProcessor(object):
def __init__(self):
self.handlers = [] # List of pairs (regexp, handler)
def register(self, regexp):
"""Declare a function as handler for a regular expression."""
def gethandler(f):
self.handlers.append((re.compile(regexp), f))
return f
return gethandler
def process(self, file):
"""Process a file line by line and execute all handlers by registered regular expressions"""
for line in file:
for regex, handler in self.handlers:
m = regex.search(line)
if (m):
handler(m.group(1))
# in log_processor.py
log_processor = GenericLogProcessor()
@log_processor.register(r'^<\w+> (.*)')
def handle_message(msg):
print msg
@log_processor.register(r'^\*{3} (.*)')
def handle_warning(msg):
global num_warnings, num_fatals
num_warnings += 1
if is_fatal(msg):
num_fatals += 1
# in your code
with open("1.log") as f:
log_processor.process(f)
https://stackoverflow.com/questions/6629876
复制相似问题