In Python, is it considered better style to:
def _sort_by_score(scoring, items_list):
unsorted_scored_list = [(scoring(len(items_list), item_position), item) for item_position, item in enumerate(items_list)]
sorted_list = [item for score, item in sorted(unsorted_scored_list)]
def _identity_scoring(items_list_size, item_position):
def _reversed_scoring(items_list_size, item_position):
return items_list_size - item_position
# Explicit function definition style
return _sort_by_score(_identity_scoring, items_list)
return _sort_by_score(_reversed_scoring, items_list)
# Curried function definition style
identity_ordering = functools.partial(_sort_by_score, _identity_scoring)
reversed_ordering = functools.partial(_sort_by_score, _reversed_scoring)
>>> foo = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
If you want to have the curried functions as part of a public interface, use explicit function definitions. This has the following additional advantages:
It is easier to assign a docstring to an explicit function definition. For
partial() functions, you would have to assign to the
__doc__ attribute, which is somewhat ugly.
Real function definitions are easier to skim when browsing the module source.
I would use
functools.partial() in a similar way to lambda expressions, i.e. for locally needed throw-away functions.
In your particular example, I'd probably use neither, drop the leading underscores and call
which seems the most explicit to me.