Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real world examples of partial function

I have been going through Python's partial function. I found it's interesting but it would be helpful if I can understand it with some real-world examples rather than learning it as just another language feature.

like image 407
sarat Avatar asked Dec 03 '22 00:12

sarat


2 Answers

One use I often put it to is printing to stderr rather than the default stdout.

from __future__ import print_function
import sys
from functools import partial

print_stderr = partial(print, file=sys.stderr)
print_stderr('Help! Little Timmy is stuck down the well!')

You can then use that with any other arguments taken by the print function:

print_stderr('Egg', 'chips', 'beans', sep=' and ')
like image 171
dhwthompson Avatar answered Dec 07 '22 22:12

dhwthompson


Another example is for, when writing Tkinter code for example, to add an identifier data to the callback function, as Tkinter callbacks are called with no parameters.

So, suppose I want to create a numeric pad, and to know which button has been pressed:

import Tkinter
from functools import partial

window = Tkinter.Tk()
contents = Tkinter.Variable(window)
display = Tkinter.Entry(window, textvariable=contents)

display.pack()

def clicked(digit):
    contents.set(contents.get() + str(digit))

counter = 0

for i, number in enumerate("7894561230"):
    if not i % 3:
        frame = Tkinter.Frame(window)
        frame.pack()
    button = Tkinter.Button(frame, text=number, command=partial(clicked, number))
    button.pack(side="left", fill="x")

Tkinter.mainloop()
like image 21
jsbueno Avatar answered Dec 07 '22 22:12

jsbueno