def foo(data):'''accepts a dict to construct something, string support in future'''if type(data) is not dict:# we're only going to test for dicts for nowraise ValueError('only dicts are supported for now')
from collections import OrderedDict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
引发错误!
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 3, in fooValueError: argument must be a dict
isinstance
但是如果我们使用isinstance,我们可以支持Liskov替换!:
def foo(a_dict):if not isinstance(a_dict, dict):raise ValueError('argument must be a dict')return a_dict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
# according to `abc.__instancecheck__`, they are maybe different! I have not found negative onetype(INSTANCE) ~= INSTANCE.__class__type(CLASS) ~= CLASS.__class__
对于isinstance:
# guess from `abc.__instancecheck__`return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})
顺便说一句:最好不要混合使用relative and absolutely import,使用project_dir的absolutely import(由sys.path添加)