Using functools.partial with default values

138 Views Asked by At

Problem

As the title suggest, I am trying to use functools.partial to create a default setting for a callable. However, some of the parameters depend on each other.

Background

Imagine I have a function _print_slice(items: list[int], start: int, end: int) that takes in a list and prints items from start to end.

_print_slice definition

def _print_slice(items: list[int], start: int, end: int) -> None:
    print(items[start:end])

I want to make a partial version of this function called print_list that prints the entire list, i.e, start = 0 and end = len(items)

print_list definition

def print_list(items: list[int]) -> None:
    _print_slice(items=items, start=0, end=len(items))

notice that print_list is just a wrapper around _print_slice. If I am not mistaken, this would be a perfect use case for functools.partial, however, I am not sure to use use partial to accomplish this given that end = len(items), please help.

Disclaimer

This is a very simplified version of the problem to highlight what I am trying to accomplish.

1

There are 1 best solutions below

0
user2357112 On

This is not a job for functools.partial. It cannot perform the kind of dependent argument computation you want. functools.partial is designed to fix argument values, not to compute them from other argument values.

(Due to the way slicing handles None endpoints, partial(_print_slice, start=None, end=None) would have the behavior you want, but that's something the list slicing implementation would handle, not something partial handles - it wouldn't generalize to other uses of partial. Also, it violates the _print_slice argument annotations.)