[Python-ideas] Syntactic sugar to declare partial functions

Fabrizio Messina zauddelig at gmail.com
Sat Aug 4 12:03:50 EDT 2018


 
Hello, I would like to propose a new method to create a partial function.

At the moment we have to load the *partial* function from the *functool* 
library, and apply it to an existing function, e.g. 

from functools import partial


def add(x: int, y: int) -> int:
    return x + y


add_2 = partial(add, 2)



While partial expose the mechanism excellently its instantiation method is, 
at times, not very friendly, I would like to propose a syntactic sugar to 
create partial functions, in the case you create a partial function using *curly 
braces*:


def add(x: int, y: int) -> int:
    return x + y

add_2 = add{2}


At the moment this causes SyntaxError so the change is retro-compatible.

In the case of key word arguments we could have:

sort_by_x = sort{key=lambda element: element.x}


That could be good as it would be an easy way to pre-load functions without 
having to eagerly compute it, but without needing to pass the entire 
function parameters to to other scopes.


# prepare the function
get_sorted_users: Callable[[], Iterator[User]] = sort{users, key=lambda user
: user.creation_date}

# continue with job at hand
...

# some where else, maybe another process
sorted_users = list(get_sorted_users())



Even create a factory method on the fly:
@dataclass
class Product:
    name: str
    category: Category
    price: Decimal


smartphone_factory = Product{category=smartphone_category}



Now all this can already be done with partial, but adding this syntactic 
sugar would reduce the perception of `partial` as an advanced feature, 
alleviating the use of closures created only for the sake of avoiding an 
explicit partial.

In my opinion this syntactic sugar has a lot of potential adoption seen the 
general interest in functional programming.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180804/78a172a1/attachment.html>


More information about the Python-ideas mailing list