-1

I'm learning Python right now and I am just trying to get to grips with all of the syntax options.

Currently, the only thing that I can't seem to google up is what to do if I for some reason want to define a function which contains multiple other defines.

While I understand what to do if there's only 1 define inside the the larger define (val = f()(3,4) returns 7 if you exclude the second def below), I don't know how to correctly use the function below.

If it's possible, what is the syntax for a def function with an arbitrary amount of defined functions within it?


Code:

def f():
    def x(a,b):
        return a + b
    return x
    def y(c,d):
        return c + d
    return y

 val = f()(3,4)(5,6)
 print(val)

I expected the above to return either (7,11) or 11. However, it returns 'int object is not callable'

  • 2
    You have to nest *deeper* if you want `f` to return `x` to return `y`. Currently `y` never even gets defined, because you `return x` before reaching it. – jonrsharpe Jan 22 '19 at 16:39
  • This is less of a syntax problem than a *semantic* problem. Understand exactly what it is you want to *do*, and the syntax is pretty much self explanatory. You want `f` to return a function that *also* returns a function; i.e., `y` is defined inside of and returned by `x`, not `f`. – chepner Jan 22 '19 at 16:59

1 Answers1

0

When you write val = f()(3,4)(5,6), you want f to return a function that also returns a function; compare with the simpler multi-line call:

t1 = f()
t2 = t1(3,4)
val = t2(5,6)

The function f defines and returns also has to define and return a function that can be called with 2 arguments. So, as @jonrsharpe said, you need more nesting:

def f():
    def x(a, b):
        def y(c, d):
            return c + d
        return y
    return x

Now, f() produces the function named x, and f()(3,4) produces the function named y (ignoring its arguments 3 and 4 in the process), and f()(3,4)(5,6) evaluates (ultimately) to 5 + 6.

chepner
  • 497,756
  • 71
  • 530
  • 681