Search code examples
pythonmap-functionpartial-application

Python partial function doesn't execute


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)

Solution

  • 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]