Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python deep nesting factory functions

Working through "Learning Python" came across factory function. This textbook example works:

def maker(N):
    def action(X):
        return X ** N
    return action


>>> maker(2)
<function action at 0x7f9087f008c0>
>>> o = maker(2)
>>> o(3)
8
>>> maker(2)
<function action at 0x7f9087f00230>
>>> maker(2)(3)
8

However when going deeper another level I have no idea how to call it:

>>> def superfunc(X):
...     def func(Y):
...             def subfunc(Z):
...                     return X + Y + Z
...     return func
... 
>>> superfunc()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: superfunc() takes exactly 1 argument (0 given)
>>> superfunc(1)
<function func at 0x7f9087f09500>
>>> superfunc(1)(2)
>>> superfunc(1)(2)(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> superfunc(1)(2)
>>>

Why doesn't superfunc(1)(2)(3) work while maker(2)(3) does?

While this kind of nesting certainly doesn't look like a good, usable code to me, Python still accepts it as valid, so I'm curious as to how this can be called.

like image 352
GSP Avatar asked Mar 27 '26 14:03

GSP


1 Answers

You get a TypeError because function func doesn't return anything (thus its return is NoneType). It should return subfunc:

>>> def superfunc(X):
...     def func(Y):
...             def subfunc(Z):
...                     return X + Y + Z
...             return subfunc
...     return func
... 
like image 60
Nadir Sampaoli Avatar answered Mar 29 '26 04:03

Nadir Sampaoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!