4

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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
sarat
  • 10,512
  • 7
  • 43
  • 74

3 Answers3

12

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 ')
dhwthompson
  • 2,501
  • 1
  • 15
  • 11
7

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()
jsbueno
  • 99,910
  • 10
  • 151
  • 209
-1

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

Community
  • 1
  • 1
Marcin
  • 48,559
  • 18
  • 128
  • 201
  • 9
    "from module import *" is bad style, do not spread it around in example snippets. – ddaa Jan 12 '12 at 12:24
  • @ddaa: I disagree. It can frequently be appropriate, such as when importing "plumbing" of general utility. – Marcin Jan 12 '12 at 12:31
  • 3
    There are some cases where it's useful (like importing all the objects from tkinter to write an application), but it's best avoided in example snippets. Doing it from two libraries is especially confusing, because it obscures where each thing comes from: which library would I find `compose` in? Oh, and did you mean `functools`, rather than `functional`? – Thomas K Jan 12 '12 at 12:51