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.
Asked
Active
Viewed 4,148 times
3 Answers
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
-
2+1 It is convenient for other GUI libraries (like PyQt, wx) too. – reclosedev Jan 12 '12 at 15:33
-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).
-
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
-
3There 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