2013-03-01 37 views
6

PEP8 E712は、「Trueとの比較はif cond is True:またはif cond:」である必要があります。ブール型numpy配列との比較VS PEP8 E712

私がこれに従うなら、PEP8私は違う/間違った結果を得ます。どうして?

In [1]: from pylab import * 

In [2]: a = array([True, True, False]) 

In [3]: where(a == True) 
Out[3]: (array([0, 1]),) 
# correct results with PEP violation 

In [4]: where(a is True) 
Out[4]: (array([], dtype=int64),) 
# wrong results without PEP violation 

In [5]: where(a) 
Out[5]: (array([0, 1]),) 
# correct results without PEP violation, but not as clear as the first two imho. "Where what?" 
+0

このPEP8 E712はどこにありますか? – mgilson

+2

これは 'pep8'ツールによる特定の診断出力です:https://github.com/jcrocholl/pep8/blob/master/pep8.py#L900。この場合、 'a is True 'は配列に関係する意味がないため、間違っていることに注意してください。 – nneonneo

+0

@mgilsonまた、Pythonの 'linter'を検索することもできます。ほとんどの/いくつかのIDEにはコードをpep8でチェックするためのプラグインがあります。 – Framester

答えて

2

このアドバイスは、値の「真実性」をテストする文ifにのみ適用されます。 numpyは別の獣です。 aがアレイではなく、ブールであり、そしてisは、単純な基準等価試験(;例えばNone is not TrueのでのみTrue is True)がないためa is Trueが常にFalseあること

>>> a = np.array([True, False]) 
>>> a == True 
array([ True, False], dtype=bool) 
>>> a is True 
False 

注意。

6

numpyのの '真の' 'true' にPythonのと同じ 'TRUE' ではありませんし、そのためのisが失敗した:

>>> import numpy as np 
>>> a = np.array([True, True, False]) 
>>> a[:] 
array([ True, True, False], dtype=bool) 
>>> a[0] 
True 
>>> a[0]==True 
True 
>>> a[0] is True 
False 
>>> type(a[0]) 
<type 'numpy.bool_'> 
>>> type(True) 
<type 'bool'> 

また、具体的には、PEP 8はDONT使用 'は' かは '==' と言いますブール値:

Don't compare boolean values to True or False using ==: 

Yes: if greeting: 
No: if greeting == True: 
Worse: if greeting is True: 

空numpyのアレイはちょうど空のPythonリストまたは空の辞書として試験falseyを行い行います

>>> [bool(x) for x in [[],{},np.array([])]] 
[False, False, False] 
Pythonの、単一falsey要素のnumpyの配列とは異なり

は、テストfalsey行います

>>> [bool(x) for x in [[False],[0],{0:False},np.array([False]), np.array([0])]] 
[True, True, True, False, False] 

をしかし、あなたは複数の要素でnumpyの配列とそのロジックを使用することはできません:「だから、

>>> bool(np.array([0,0])) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

>>> np.where(np.array([0,0])) 
(array([], dtype=int64),) 
>>> np.where(np.array([0,1])) 
(array([1]),) 

または使用any:numpyのとPEP 8の精神は」唯一の各要素のtruthinessをテストするために、おそらくです

>>> np.array([0,0]).any() 
False 
>>> np.array([0,1]).any() 
True 

そして、これはあなたが期待するものではないことに注意してください:

>>> bool(np.where(np.array([0,0]))) 
True 

np.whereが空のタプルを返しているので。