Syntax Suggestion: Pass Function Definition as Argument

Antoon Pardon antoon.pardon at vub.be
Fri Nov 8 06:54:53 EST 2019


On 7/11/19 18:10, Stephen Waldron wrote:
> What I'm aiming for is the ability to, within a function call, pass a suite that would be there automatically defined by the compiler/interpreter. Another comment did mention lambda functions, which does to some degree provide that capability, but is restricted to well, lambda functions (only expressions, not statements).
I don't think those restrictions are that limiting. Certainly not since
python3.8 and python acquired an assigment operator. And you should also
note that a list is an expression. So we could do something like the
following.

class Book:
    def __init__(self, name, author):
        self.name = name
        self.author = author


def doToBooks (bookList, first, then, book = None):
    
    for book in bookList:
        first(book = book)
        then(book = book)

myBooks = [
    Book("The Way of the World", "Lucy Cole"),
    Book("To Live or To Love", "Georgio Dunham"),
    Book("Twelve Days of Success", "Anita Duvette")
]
import sys
write = sys.stdout.write

doToBooks (myBooks,
           first = lambda book: [write(book.name), write("\n")],
           then = lambda book: [write(" - "), write(book.author), write("\n")]
          )

The above code will print the following:

The Way of the World
 - Lucy Cole
To Live or To Love
 - Georgio Dunham
Twelve Days of Success
 - Anita Duvette

-- 
Antoon.



More information about the Python-list mailing list