31

Apparantly it will (in the 'future') not be possible anymore to use the following:

import numpy as np
np.array([0,1,2]) == None
> False
> FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.

This also breaks the lazy loading pattern for numpy arrays:

import numpy as np
def f(a=None):
    if a == None: 
        a = <some default value>
    <function body>

What other possibilities allow you to still use lazy initialization?

Matthias
  • 4,481
  • 12
  • 45
  • 84

1 Answers1

62

You are looking for is:

if a is None:
    a = something else

The problem is that, by using the == operator, if the input element a is a numpy array, numpy will try to perform an element wise comparison and tell you that you cannot compare it.

For a a numpy array, a == None gives error, np.all(a == None) doesn't (but does not do what you expect). Instead a is None will work regardless the data type of a.

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
  • so from a Java point of view, the `is` is considered as a reference check whereas the `==` is considered as an `equals()` check (that could be overriden and if not overriden it's just a reference check) – Matthias Nov 27 '15 at 09:37
  • 1
    @Matthias Exactly. From a java point of view, the python's `==` would trigger java's `.equals`, which in `numpy` is overrided to perform a *element-wise check*. Python's `is` would be equivalent to check for reference in java (similar to using `==` with strings). However, for strings in python (i.e. `a = 'hello'; b = 'hello'`), the `a is b` would still return true, as both of them are the same constant (`'hello'`). – Imanol Luengo Nov 27 '15 at 09:40
  • 1
    @Matthias have a look [this excellent answer](http://stackoverflow.com/questions/13650293/understanding-pythons-is-operator), for further detail of the `is` operator. – Imanol Luengo Nov 27 '15 at 09:44
  • 1
    the last comparison will be true in Java as well (or is VM dependent?) – Matthias Nov 27 '15 at 09:46
  • @Matthias to be honest, it's been a long time without programming in Java, so it might be haha. Just wanted to point out the behaviour in python =P – Imanol Luengo Nov 27 '15 at 09:48