Wählen Sie die Python-Funktion zum Aufrufen basierend auf einer Regex

Ist es möglich, eine Funktion in einer Datenstruktur, ohne zuerst geben Sie einen Namen mit 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?

Den Körper einer lambda-Funktion ist stark eingeschränkt, so kann ich Sie nicht benutzen.

Edit: als Referenz, dies ist mehr wie real-life-code, wo ich das problem aufgetreten ist.

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) )

InformationsquelleAutor der Frage Tim | 2011-07-08

Schreibe einen Kommentar