0

I'm passing an argument(lets say the variable 'a') to a function, and this variable can either equal None or be a np.array.

# Option 1
a = None

# Option 2
a = np.array(range(0,10))

Depending on what a equals, I want to do different things.

This is what I did:

if a == None:
     do this
else:
     do that

The problem with this is that a np.array cant equal None and I get the following message: "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

However, if I use a.any() or a.all() and a = None, a different error pops up because None doesn't have the attribute 'any' or 'all'.

How can I fix this in a nice way?

I tried the following but it seems that there must be a better way than duplicating code, or am I wrong?

try:
     if a == None:
          do this
     else:
          do that
except:
     if a.any() == None:
          do this
     else:
          do that
0

2 Answers 2

1

Use is instead of ==:

if a is None:
     do this
else:
     do that
Sign up to request clarification or add additional context in comments.

Comments

1
if isinstance(a, np.ndarray):
    ...
else:
    ...

or

if type(a) is np.ndarray:
    ...
else:
    ...

or

if a is None:
    ...
else:
    ...

They all will work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.