Partial functions in Python are SUPER NEAT

preview_player
Показать описание
Partials are a little known of Python that can prove incredibly useful! They allow you to create partial objects in place of brand new functions, making code readable, as well as a little more performant!



If you want to see more of me, join my Discord server!

I get a lot of people asking, so here's my setup!



If you have any questions, don't hesitate to ask in the comments! I'll try and answer as soon as I can, providing someone else hasn't already done so.

#python #coding #howto
Рекомендации по теме
Комментарии
Автор

I use partial functions in tkinter. Say you have a whole load of buttons that you want to use the same call back function. You can make the call back function take an argument specifying which button was pressed. But the button wants a callback function with zero args so you can use a partial function.

TonyDig
Автор

Looks like the functools module is implemented in c instead of python, which is interesting. I didn't read the code for partial carefully, but there is something interesting, looks like it doesn't add anything extra to the call stack.

I tried something like:

def x(a, b):
raise Exception("test")

y = partial(x, 1)

y(2)

That shows this traceback:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in x
Exception: test


If y is instead a lambda or wrapper function then we have;

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in y
File "<stdin>", line 2, in x


Which kind of makes it look like the function is being rewritten.

edgarcabrera
Автор

this is very interesting. In engineering we have formulas that often have different keyword argument values for units.

It could be nice to use a partial to interchange metric and imperial units for example for constants

nascentnaga
Автор

Underrated channel, also that bri-ish accent is

advik-b
Автор

yo, ur content is amazing, tysm. BTW please, what is that Terminal configuration that it looks sooo good, is it any Vim related? luv u man

cosmiclattemusic
Автор

As a functional programmer from Canberra, this bizarro world video title and channel name was very confusing. Glad to see Python providing ways to do programming the way it should be!

Can you partially apply more than one argument at a time? Like can you make a partial from a three argument method, then apply it to one argument, then apply that to the second?

Axman
Автор

Curried python. Yum.

4:09 I'm not sure why partials are more optimised but my uneducated guess is maybe lambda is a closure and has that overhead, whereas partial creates a function and doesn't have that problem (and partial probably handles the wiring up at a layer closer to the bare metal)

orterves
Автор

What a coincidence, I'm eating curry right now

murphygreen
visit shbcf.ru