Luca
Luca

Reputation: 10996

specify in place operation in a python function

Currently I have a python function that takes a numpy array and modifies it in place and I would like the user to be able to be able to choose this. So, currently, it is as:

def my_func(signal, filter):
    ...
    # Compute the filter weights
    signal *= filter

So I want to do something like:

def my_func(signal, filter, inplace=True):
   ...
   # Compute filter_weights
   if inplace:
       signal *= filter
   else:
       out = np.copy(signal)
       out *= filter
       return out

But the problem is that now we have one execution path that returns an output and the other which does not return anything. I am wondering if this is the correct approach or if there is a more pythonic way to do this.

Upvotes: 2

Views: 427

Answers (1)

jure
jure

Reputation: 412

I would go with your current version, if you do not want to provide two functions.

As an example, the Pandas library provides sort method for its container, that works as your example. If the sorting is done inplace, by providing the inplace=True, nothing is returned, otherwise a sorted copy is returned.

Upvotes: 1

Related Questions