1

Is there a meaningful difference between these two?

class StatefulPredicate:
    state = None  # Something initial.

    def __call__(self, arg) -> bool:
        previous = self.state
        self.state = arg  # Something based on arg.
        return arg != previous  # Something based on previous and arg.


print(list(itertools.takewhile(StatefulPredicate(), [1, 2, 3, 3, 4])))

def stateful_predicate():
    def predicate(arg) -> bool:
        previous = predicate.state
        predicate.state = arg  # Something based on arg.
        return arg != previous  # Something based on previous and arg.
    predicate.state = None  # Something initial.
    return predicate

print(list(itertools.takewhile(stateful_predicate(), [1, 2, 3, 3, 4])))

I find the former more intuitive.

Tobias
  • 3,882
  • 2
  • 22
  • 25
  • 1
    You can create derived classes from the class. – Michael Butscher Dec 19 '21 at 23:33
  • I prefer the former as well. You instantly think "custom object" when seeing the `class` keyword, while it takes longer to see it in the function definition. – Guimoute Dec 19 '21 at 23:33
  • 1
    Just [another](https://tio.run/##bZDBCsIwDIbvfYp4a6EIOg8i7BU8eROR4aIWa1vSTN3Tz25iJ7gQAv3y/@UnoeWrd8U6UNeZe/DEYBiJvbdRiBrPELliPDf2GAhrc0oPqTYCUvXbP9hXgg/jm6ihoguUsPUONcjWoK1VVj2vxiLsqMHROeVO82seyKzMks9nOQOUv3mGncMXyww/jJAbcqN0HtHVQgQyjqU1kWU@wZyrGw5B5dQdNOwXGpYaiqFXB6VU170B)... – Kelly Bundy Dec 19 '21 at 23:45
  • @MichaelButscher Good point. I can also make stateful_predicate take two lambdas. – Tobias Dec 20 '21 at 00:01
  • @KellyBundy the question is not exactly where to put the state, but you could win that one. – Tobias Dec 20 '21 at 00:10
  • 1
    Your second one could replace the function attribute with a non-local variable that the closure `predicate` has access to. There's a saying that nicely captures the duality between classes and closures: a class is data with code, while a closure is code with data. Which you use is largely a matter of preference. – chepner Dec 20 '21 at 01:09
  • The saying has been put [more colorfully](https://stackoverflow.com/a/501053). – Davis Herring Dec 20 '21 at 02:28

0 Answers0