2 ms·
At the same time, if your function has an expensive initialization step that only needs to be called once (and doesn't change between calls), then the pattern o
by fastball 6y ago
At the same time, if your function has an expensive initialization step that only needs to be called once (and doesn't change between calls), then the pattern of using `__init__()` + `__call__()` can be very nice.
- im3w1l 6y agoI would consider this pattern: def x(): expensive precompute def y(): cheap stuff return y It's a matter of taste I guess.
- fastball 6y agoFor comparisons sake: class Thing: def __init__(self, arg): # expensive precompute self.result = ... def __call__(self, arg): # cheap stuff that uses self.result for something ... And then usage is: f = Foo("some val") bar = f("another val") So yeah, both definitely do the same job. And your pattern is probably faster. But I generally like using Python's dunder methods as I think they allow for more consistent/recognizable code patterns.