python 3.x - Why does type(mock.MagicMock()) == mock.MagicMock returns False? -
in python3.4:
>>> import mock.magicmock >>> type(mock.magicmock()) == mock.magicmock false # huh, why that? >>> isinstance(mock.magicmock(), mock.magicmock) true
when simplify class a
, b
type(b()) == b
returns true
:
>>> class a: pass >>> class b: pass >>> class c(a, b): pass >>> type(b()) == b true # of course of study say.
why returns type(mock.magicmock()) == mock.magicmock
false
? know difference between isinstance()
, type()
in python. type()
doesn't 'understand' subclassing isinstance
does. don't see how difference involved here.
source of mock.magicmock
.
more experiments suggest answer.
>>> unittest.mock import magicmock mm >>> mm1 = mm() >>> mm2 = mm() >>> type(mm1) <class 'unittest.mock.magicmock'> >>> type(mm2) <class 'unittest.mock.magicmock'> >>> type(mm1) == type(mm2) false >>> id(type(mm1)) 53511896 >>> id(type(mm2)) 53510984 >>> type(mm1) mm1.__class__ true >>> mm <class 'unittest.mock.magicmock'> >>> id(mm) 53502776
conclusion: each instance of magicmock has 'class' looks magicmock, not. new creates such instances? magicmock subclasses mock, subclasses noncallablemock, has new method.
def __new__(cls, *args, **kw): # every instance has own class # can create magic methods on # class without stomping on other mocks new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__}) instance = object.__new__(new) homecoming instance
the new = ...
statement creates subclass of cls
argument same name , docstring. next line creates single instance of subclass. mocks follow revised equality instead of type(mm()) mm
.
>>> mm.__bases__ (<class 'unittest.mock.magicmixin'>, <class 'unittest.mock.mock'>) >>> type(mm1).__bases__ (<class 'unittest.mock.magicmock'>,) >>> type(mm1).__bases__[0] mm true
python-3.x typechecking
No comments:
Post a Comment