I just realized that Python classes give you a filter predicate for free.

I guess I’m really late to the party, but this is a new realization for me. I have a class for info about a single code recipe on forkful.ai. Here’s a simplified version:

class Article:
    def __init__(self, title, language):
        self.title = title
        self.language = language

    def is_english(self) -> bool:
        return self.language == 'English'

In my Python script that manages the content, a list of articles_to_create is built. For a technical reason which I’ll blog about later, I need an Iterable of only the English articles.

I went through these steps in refactoring and realization:

return (a for a in articles_to_create if a.is_english())

That definitely works, but the a for a thing always bugs me as unexpressive fluff. How would filter look?

return filter(lambda a: a.is_english(), articles_to_create)

Ah, it’s wordy because of lambda syntax, but I think it’s more directly expressive of the purpose of the code.

And I wondered, how hard would it move the lambda creation function to Article? And I realized, “Wait a minute! Article.is_english already produces the same results as that lambda: it accepts an instance as a parameter and calls .is_english() on it. It returns a boolean:

return filter(Article.is_english, articles_to_create)

Pretty sweet. Anyone else use this to shorten down your code and make it more expressive?

Leave a Comment