简体   繁体   中英

a simplified signature in functools.partial

In the official docs to explain functools 10.2. functools — Higher-order functions and operations on callable objects — Python 3.7.0 documentation

The partial() is used for partial function application which “freezes” some portion of a function's arguments and/or keywords resulting in a new object with a simplified signature . For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

I could understand most of the statement and admit the "freeze" is a delicate and accurate word to describe the context.

What I cannot follow is "a simplified signature",
What kind of signature it refers for?

In this context, simplified just means fewer arguments. If you have

import functools

def func(a, b, x=8, y=9):
    print((a, b, x, y))

simple_func = functools.partial(func, 1, x=2)

, then simple_func ends up a function with one argument a and one keyword argument y :

>>> simple_func(3, y=4)
(1, 3, 2, 4)

A function signature is the name of the function, its parameters and, strictly speaking, its return type:

mymodule.myfunction(foo, bar=None, *, baz=42)

This is the signature . When you partial ly bind a function, it returns a new function, typically with fewer parameters because you have already bound a few arguments:

partial(mymodule.myfunction, bar='Mike')

The signature of this newly partially bound function is:

func(foo, *, baz=42)

A simpler signature than the original one.

The signature means how the function is called, if you have a function that needs five strings its signature is

foo (st1, st2, st3, st4, st5)

If you now use partial to freeze three of them, it only needs two

foo (st1, st2)

Which is "simplified" because it needs less parameters.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM