0

I have a function with multiple parameters, some of which should be optional. I want the parameters to be able to work with numpy arrays. If the parameters are given, when the function is called, I want to perform operations. I'm trying to use something similar to this (the actual operation is more complex):

def func(a, b = None, c = None):
    a*2
    if b != None:
        b*2
        if c != None:
            c*2

This works well, as long as I don't pass an array into these optional parameters. When I pass an array for b or c the if b != None doesn't work without any() or all(). If I change it, it does work when all optional arguments are used, but no longer if they're not used.

Is there a way to use something instead of None which will allow me to use an if-statement for the default value/object as well as an array I pass into the function.

It should look similar to this (with something different than None):

def func(a, b = None, c = None):
    a*2
    if b.all() != None:
        b*2
        if c.all() != None:
            c*2

I would also appreciate any better ways to simply ask if an optional parameter was given to a function.

Weena
  • 55
  • 1
  • 6

1 Answers1

4

Do not use != here; you are testing if all values of an array are not equal to None. Instead, use is identity testing:

if b is not None:
    # ...

is and is not do not broadcast across an array.

You should always use is and is not when testing for None anyway, because it is guaranteed to be a singleton.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343