-1

I'm new to using partial functions in Python. Here's a piece of simple code, and I am expecting it to print out results, but somehow it doesn't print anything, or say otherwise show that firstfunc gets executed:

from functools import partial

class zebra(object):
    def firstfunc(self, a, b, c):

        res = 3*a + 55*b + c
        print(res)
        return res

    def partial_func(self, a, c):
        return partial(self.firstfunc, b = 2)


myzebra = zebra()
alist = [1, 2, 3, 4]
blist = [7, 8, 9, 11]

map(myzebra.partial_func, alist, blist)
duplode
  • 33,731
  • 7
  • 79
  • 150
viva
  • 13
  • 4
  • what is the problem? you can't execute `firstfunc`? as it's defined in the commented line or what? – pivanchy Jan 23 '16 at 19:36
  • hi, i am expecting it to print out 393 451 509 622, but it doesn't print out anything, seems like whatever in firstfunc never get execute – viva Jan 23 '16 at 19:37
  • @viva: `map()` calls `myzebra.partial_func`. `map()` cannot know that you wanted it to call the returned `partial()` object *too*. – Martijn Pieters Jan 23 '16 at 19:41
  • @viva: and presumably this is Python 2, not 3, because in Python 3 `map()` loops lazily (it is a iterator). – Martijn Pieters Jan 23 '16 at 19:42

1 Answers1

2

Your myzebra.partial_func() is called, and it returns a partial function object. If you wanted it that to be called as well, do so in myzebra.partial_func():

def partial_func(self, a, c):
    return partial(self.firstfunc, b = 2)(a=a, c=c)

or use a lambda in the map() to call it for you:

map(lambda a, c: myzebra.partial_func(a, c)(a=a, c=c), alist, blist)

Note that because you made b a keyword parameter, you'll have to pass at least c as a keyword parameter too.

map() won't recursively call objects; only the outermost object is called.

In Python 2, the code now works:

>>> map(lambda a, c: myzebra.partial_func(a, c)(a=a, c=c), alist, blist)
120
124
128
133
[120, 124, 128, 133]

In Python 3, map() loops lazily, so you need to iterate over it for it to execute:

>>> list(map(lambda a, c: myzebra.partial_func(a, c)(a=a, c=c), alist, blist))
120
124
128
133
[120, 124, 128, 133]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343