user14518163
user14518163

Reputation: 11

Python interpretation of a possible functional programming

I am reading a Python script which has this syntax a, b = foo(c, d)(f, g). It is the first time I am seeing this syntax. How do I have to interpret that?

Unfortunately I am not authorized to share the code.

foo has a structure like the following.

def foo(n):
   def todo(func):
      def dodo(*args, **kargs):
         ...
         ...
         ...
         return func(*args, **kargs)
      return dodo
   return todo

Upvotes: 0

Views: 76

Answers (1)

awdr
awdr

Reputation: 72

Hia all, a,b = foo(c,d)(f,g) means

  1. Execute foo with args c and d (returns a function) (foo(c,d))
  2. Execute the function returned with args f and g (returns a list with lenth 2) (foo(c,d)(f,g) (func(f,g)))
  3. assign a the first item of the list (a,b = foo(c,d)(f,g) (a = foo(c,d)(f,g)[0]))
  4. assign b the second item of the list (b = foo(c,d)(f,g)[1])

so a,b = foo(c,d)(f,g) is a way to write

save = foo(c,d)(f,g)
a = save[0]
b = save[1]

Examples:

(warning: c,d,f and g as are ints in my Examples)

foo returns a function. Example:

def foo(c,d):
    if c+d > 10:
        return func1
    else:
        return func2

so you execute func1 (or func2) with f and g,

then you save output 1 to a and output2 to b

Example for func1 and func2:

def func1(f,g):
    return [f+1,g+1]
def func2(f,g):
    return [f-1,g-1]

then would the snippet would be used as following:

c = 5
d = 8
f = 19
g = 4
def func1(f,g):
    return [f+1,g+1]
def func2(f,g):
    return [f-1,g-1]

def foo(c,d):
    if c+d > 10:
        return func1
    else:
        return func2

a,b = foo(c,d)(f,g)

if we add prints to the end then

a will be 20

and b will be 5.

Upvotes: 3

Related Questions