python - 根据正则表达式选择要调用的 Python 函数

标签 python anonymous-function lambda

是否可以将函数放入数据结构中,而无需先用 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) )

最佳答案

这是基于 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

关于python - 根据正则表达式选择要调用的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6629876/

相关文章:

java - 为什么 Java 8 提供方法引用?

python - 解决 scikit-learn One Vs Rest 随机森林的缓慢解封问题

c# - foreach 循环中的匿名委托(delegate)

JavaScript 和柯里化(Currying)

scala - 如何在 scala 中使用泛型创建部分函数?

c++ - 何时使用函数模板而不是通用 lambda?

java - Log4j2 在方法引用调用中打印实用程序类行号

python - 在 pyvis 中更改图形布局(又名节点定位算法)

python - 我在 python 中使用startswith匹配一行后找到下一行,但行之间有多个空格

python - 动态创建包含人员年龄(以月份为单位)的 DataFrame 的最 Pythonic 方法是什么?