0

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
4
  • The function foo(c, d) is probably returning another function that accepts two parameters. Commented Oct 25, 2020 at 20:00
  • 1
    and that function returns a 2-tuple, a 2-list or something that can be decomposed into a,b - but without the implementation of foo this is not really answerable nor is it in and of itself a good question for SO. Commented Oct 25, 2020 at 20:01
  • Some function (or other callable) is being returned (and possibly created by) the object named foo (itself a function or other type of callable). The latter is returning a sequence of some of length 2 whose element are being "unpacked" and assigned to the variables a & b. Commented Oct 25, 2020 at 21:06
  • @Patrick: I disagree. The OP seems to only be asking how to understand what the code shown should be interpreted as doing (generally or abstracty). Commented Oct 25, 2020 at 21:09

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.