functional programming - In Python, partial function application (currying) versus explicit function definition -
in python, considered better style to:
- explicitly define useful functions in terms of more general, possibly internal use, functions; or,
- use partial function application explicitly describe function currying?
i explain question way of contrived example.
suppose 1 writes function, _sort_by_scoring, takes 2 arguments: scoring function , list of items. returns copy of original list sorted scores based on each item's position within original list. 2 example scoring functions provided.
def _sort_by_score(scoring, items_list): unsorted_scored_list = [(scoring(len(items_list), item_position), item) item_position, item in enumerate(items_list)] sorted_list = [item score, item in sorted(unsorted_scored_list)] return sorted_list def _identity_scoring(items_list_size, item_position): return item_position def _reversed_scoring(items_list_size, item_position): return items_list_size - item_position
the function _sort_by_score never called directly; instead, called other single-argument functions pass scoring function , lone argument (a list of items) _sort_by_scoring , return result.
# explicit function definition style def identity_ordering(items_list): return _sort_by_score(_identity_scoring, items_list) def reversed_ordering(items_list): return _sort_by_score(_reversed_scoring, items_list)
obviously, intent better expressed in terms of function currying.
# curried function definition style import functools identity_ordering = functools.partial(_sort_by_score, _identity_scoring) reversed_ordering = functools.partial(_sort_by_score, _reversed_scoring)
usage (in either case):
>>> foo = [1, 2, 3, 4, 5] >>> identity_ordering(foo) [1, 2, 3, 4, 5] >>> reversed_ordering(foo) [5, 4, 3, 2, 1]
apparent advantages of explicit function definition style:
- useful functions may defined before more general functions are, without raising nameerrors;
- helper functions (e.g., scoring functions) defined within function definition body;
- possibly easier debug;
- code looks nice virtue of "explicit better implicit."
apparent advantages of curried function definition style:
- expresses intent of functional programming idiomatically;
- code looks nice virtue of succinctness.
for defining "useful" functions, of 2 styles preferred? there other styles more idiomatic/pythonic/etc.?
if want have curried functions part of public interface, use explicit function definitions. has following additional advantages:
it easier assign docstring explicit function definition.
partial()
functions, have assign__doc__
attribute, ugly.real function definitions easier skim when browsing module source.
i use functools.partial()
in similar way lambda expressions, i.e. locally needed throw-away functions.
in particular example, i'd use neither, drop leading underscores , call
sort_by_score(identity_scoring, foo)
which seems explicit me.
Comments
Post a Comment