[Numpy-discussion] Add pad_to_shape and pad_to_match for simpler padding if a target size is already known

Ralf Gommers ralf.gommers at gmail.com
Sat Apr 24 11:54:28 EDT 2021

On Thu, Apr 15, 2021 at 11:54 AM czorio4 <czorio4 at gmail.com> wrote:

> Hello all,
> I'm only two weeks late with this message about my pull request
> <https://github.com/numpy/numpy/pull/18707> that adds functions that
> allow the user to pad to a target shape, instead of adding a certain amount
> to each axis.

No worries at all, things often go at "whenever I have some time after life
stops getting in the way" pace here.

> For example:
>     x = np.ones((3, 3))
>     # We want an output shape of (10, 10)
>     padded = np.pad_to_shape(x, (10, 10))
>     print(padded.shape)
>     prints: (10, 10)
> Whereas with the current implementation of np.pad you'd need to first
> figure out the difference in axis sizes. The proposed function would
> perform this step for you. As this function passes to np.pad internally, I
> made sure to include the arguments in the signature that np.pad uses for
> padding modes.
> Finally, I've added a logical extension of this function; pad_to_match,
> this takes another array and pads the input array to match.

Adding this functionality makes sense - if we find a good place outside of
the main namespace, as was also remarked on in your PR. Luckily there is
plan to create such a space, as submodules under `numpy.lib`. This draft PR
needs to be finished for that: https://github.com/numpy/numpy/pull/18447

> These calls would be equivalent:
>     x = np.ones((3, 3))
>     y = np.zeros((10, 10))
>     padded_to_shape = np.pad_to_shape(x, y.shape)
>     padded_to_match = np.pad_to_match(x, y)

Question, why two functions with slighty awkward (double underscores) names
rather than:

    def pad_to(x, shape=None, like=None):

Note also the `like` instead of `match`; this seems more consistent with
functions like `ones_like` and the `like=` keyword which also take a shape
from another array.

> For additional functionality description, I refer to the pull request.
> I'm not too familiar with mailing lists, so I hope this is how things work.

Yep, you got it all right. Mailing lists are starting to get old-fashioned,
one of these days we'll move to something more modern.


> Kind Regards,
> Mathijs
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/numpy-discussion/attachments/20210424/52e86969/attachment-0001.html>

More information about the NumPy-Discussion mailing list