What is the Python way of chaining maps and filters?

If you don’t mind using a package, this is another way to do it using https://github.com/EntilZha/PyFunctional

from functional import seq

def as_item(x):
    # Implementation here
    return x

def is_in_stock(x):
    # Implementation
    return True

def transform(item):
    if item.type == "cake":
        catalog_item = retrieve_catalog_item(item.id);
        return {
            'id': item.id,
            'weight': item.weight,
            'barcode': catalog_item.barcode
        }
    else:
        return default_transformer(item)

low_weight_items = seq(inventory)\
    .map(as_item)\
    .filter(is_in_stock)\
    .filter(lambda item: item.weight < 1000)\
    .map(transform)

As mentioned earlier, python lets you use lamdba expressions, but they aren’t flexible as clojures in javascript since they can’t have more than one statement. Another annoying python thing are the need for backslashes. That being said, I think the above most closely mirrors what you originally posted.

Disclaimer: I am the author of the above package

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)