0

I have a class MyClass which stores an integer a. I want to define a function inside it that takes a numpy array x of length a, but I want that if the user does not pass in anything, x is set to a random array of the same length. (If they pass in values of the wrong length, I can raise an error). Basically, I would like x to default to a random array of size a.

Here is my attempt at implementing this

import numpy as np 
class MyClass():
    def __init__(self, a):
        self.a = a
    def function(self, x = None):
        if x == None:
            x = np.random.rand(self.a)
        # do some more functiony stuff with x

This works if nothing is passed in, but if x is passed in I get ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() i.e. it seems numpy doesn't like comparing arrays with None.

Defining the default value inline doesn't work because self is not in scope yet.

Is there a nice pythonic way to achieve this? To sum up I would like the parameter x to default to a random array of a specific, class-defined length.

1
  • The error is caused by doing a == test on an array. Such a test produces a boolean array of the same size. Does if [True,False,True,False]: make sense? Fortunately in this case is None is the right alternative. Commented Mar 20, 2018 at 16:32

1 Answer 1

4

As a rule of thumb, comparisons of anything and None should be done with is and not ==.

Changing if x == None to if x is None solves this issue.

class MyClass():
    def __init__(self, a):
        self.a = a

    def function(self, x=None, y=None):
        if x is None:
            x = np.random.rand(self.a)
        print(x)

MyClass(2).function(np.array([1, 2]))
MyClass(2).function()
#  [1 2]
#  [ 0.92032119  0.71054885]
Sign up to request clarification or add additional context in comments.

1 Comment

This is actually one of the key reasons Python encourages is None instead of == None, and yet whenever people answer questions on “why are we supposed to use is None”, I forget—I mean those people forget—and instead focus on the original reasons and various less important things instead...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.