pythonのすべてのバージョン(27,33,34,35,36およびpypy)で動作するはずのPythonライブラリのテストを行っています。私のテストでは、datetime
ライブラリを嘲笑しています。それらをすべて私がpypy
で実行した場合を除いて動作します(これは以前の太字の理由を参照してください)。最後の行はFalse
返す全てのPythonのバージョンでpypyでdatetimeライブラリを擬似すると、2つの模擬オブジェクトを比較するときにTypeErrorが発生する
import mock
import datetime as dtl
mk = mock.Mock(wraps=dtl.datetime)
p = mock.patch('datetime.datetime', mk)
p.start()
from datetime import datetime
d1 = datetime.now()
d2 = datetime.now()
print d1 == d2
:
はここでトラブル私がいるためMCVEです。 pypy
では最後の行はスロー:
>>>> d1 == d2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pypy/lib_pypy/datetime.py", line 1764, in __eq__
if isinstance(other, datetime):
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
私は問題を理解しようとしているpypy
のソースコードを掘り、そしてなぜ地球上でそれと他のPythonのバージョン間の違いがある、と私は以下のが見つかりました:
# Comparisons of datetime objects with other.
def __eq__(self, other):
if isinstance(other, datetime):
return self._cmp(other) == 0
elif hasattr(other, "timetuple") and not isinstance(other, date):
return NotImplemented
else:
return False
この種の意味があります。 datetime
クラスは今度はMock
オブジェクトです。そして、pythonは、isinstance
の2番目の引数が型になると主張しています。 Neato。
datetime
のCPythonとの実装を見て決めた、と驚き驚き:
# Comparisons of datetime objects with other.
def __eq__(self, other):
if isinstance(other, datetime):
return self._cmp(other, allow_mixed=True) == 0
elif not isinstance(other, date):
return NotImplemented
else:
return False
同じ正確な検証がここで行われ、まだそれが何か¯\_(ツ)_/¯
は発生しません。
私はこれのpython 2.7で起こることを追加します:
- はなぜ地球上で、それはCPythonのために働くん:
>>> d = datetime.now() >>> d datetime.datetime(2017, 9, 7, 9, 31, 50, 838155) >>> d == d True >>> datetime <Mock id='139788521555024'> >>> isinstance(d, datetime) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
私は苦労してる2つの質問がありますか?
- どのように私は、これは
__eq__
またはその他の魔法の方法を再実装することなく動作するような方法でDateTimeオブジェクトを模擬することができます:) 多くの義務が
!