Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

python - Comparison to `None` will result in an elementwise object

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...