pythonnumpydryselfshorthand

Shorthand self reference in Numpy indexing expressions


Is there a more efficient way to reference the outer array in a NumPy array indexing expression? I often find that with verbosely named NumPy arrays, the indexing expressions get ugly real fast. For example:

other_precice_array = precicely_named_array[(precicely_named_array > num) | (precicely_named_array.isodd())]

To me, using three references to "precicely_named_array" seems a bit unweildy. I would really prefer to be able to refer to the array in shorthand while indexing like so:

other_precice_array = precicely_named_array[(self > num) | (self.isodd())]

or

other_precice_array = precicely_named_array[(np.me > num) | (np.me.isodd())]

This syntax would also have the added benefit of making it more obvious when the array being sliced was dependent on a different array. See:

other_precice_array = precicely_named_array[(different_array > num) | (self.isodd())]

Is there any way to do that? Or a reason that I'm missing as to why I don't really want this?

I thought that the functions like np.where and np.choose might offer a solution, but they still require multiple references to the sliced array.

P.S. I realize that there are other ways to make the expression cleaner like separating the slicing expression into it's own variable, or just using shorter names, but for the purpose of this question I'm not interested in those answers.


Solution

  • With Python 3.8+, use a temporary variable name with the walrus operator :=.

    other_precice_array = (_ := precicely_named_array)[(_ > num) | _.isodd()]