Sunday, July 6, 2014

45. Python partial

Python's partial function, is often used in Kivy. A simple program is written to illustrate what a partial is.




These are the imports. The first one is here, so the print function will be treated the same in Python 2.7 and Python 3 versions. The important import is the next one, the partial function from the functools module.




A simple function, calculate, is defined. It needs 3 parameters. Next we create 4 variables. The variable, A, points to the particular function. B is A evaluated at a particular point. C is a partial function. C is evaluated, and the answer is in D. Next, we print the 4 variables.




For variables, A and C, you get an address, so a permanent reference can be made. This will be seen to be important in Kivy. Also C becomes agrument-less as all arguments are inside the partial function. We can see that, B and D are the same number.




The reason for the name, partial, is that you can create a function that sets some of the arguments. For example, if there was a function that required ten, or so, parameters it would make more sense to write partials if some of the parameters are fixed.


# par.py

from __future__ import print_function
from functools import partial

def calculate(a,b,c):
    return 2*a+3*b+4*c

A=calculate
B=A(1,2,3)
C=partial(calculate,1,2,3)
D=C()

print('A:{}\nB:{}\nC:{}\nD:{}'.format(A,B,C,D))

E=partial(calculate,1,2)
F=E(3)
print('F =',F)



In Kivy, we use partial whenever we want to pass parameters and we want to give a permanent reference for the callback. This is seen in the fact, that this is really an address, and not a value. We have to understand that, even though the name is partial, we do not have to actually give it a partial number of arguments.




2 comments:

  1. Python:

    Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    https://www.emexotechnologies.com/online-courses/python-training-in-electronic-city/

    ReplyDelete
  2. thank you. visit
    web programming tutorial
    welookups

    ReplyDelete