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.
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 ')
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With