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.
_______________________________________________
Python-ideas mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/