mchristos
mchristos

Reputation: 1909

Set default value as numpy array

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.

Upvotes: 0

Views: 2774

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

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]

Upvotes: 4

Related Questions