sarat
sarat

Reputation: 11120

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.

Upvotes: 4

Views: 4400

Answers (3)

jsbueno
jsbueno

Reputation: 110271

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()

Upvotes: 7

dhwthompson
dhwthompson

Reputation: 2509

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 ')

Upvotes: 12

Marcin
Marcin

Reputation: 49826

Look at my question here: Does python have a built-in function for interleaving generators/sequences?

from itertools import *
from functional import *

compose_mult = partial(reduce, compose)
leaf = compose_mult((partial(imap, next), cycle, partial(imap, chain), lambda *args: args))

You will see that I have used partial application to create single-argument functions which can be passed to iterator functions (map and reduce).

Upvotes: -1

Related Questions