In Python 3 you can create classes like this:
class foo:
def __init__(self, x):
self.x=x
def __call__(self, y):
self.x = self.x + 1
return (self.x, y)
And then one can use it as a functor with a state like this:
functor = foo(5)
x = 44354234
print('(1.1) ', functor(7))
print('(1.2) ', functor(8))
print('(1.2) ', functor(9))
In practice I've created a function that returns a function. However, this first function actually is a constructor that returns a callable object. IMHO this opens up a can of worms by allowing developers to extend the class, add methods, etc etc. Moreover, the code in __init__
somehow naturally precedes that of the code in __call__
as it needs to be executed, and that's not clear within the class-construct. Finally, the Python 3 'way' suggests to use functions over classes.
For this reason I created a similar function-version of the class, which has less boilerplate code and IMHO reads more natural:
def bar(x):
def f(y):
nonlocal x
x = x + 1
return (x,y)
return f
functor2 = bar(5)
x = 345234234
print('(2.1) ', functor2(7))
print('(2.2) ', functor2(8))
print('(2.3) ', functor2(9))
However, it uses nonlocal
and might not be intuitive for reasons I have not thought of. Is the second approach good practice, or are there dangerous pit-culls? Which should be preferred in Python 3? Especially since I have little experience with the use of nonlocal
.