deffoo(data): '''accepts a dict to construct something, string support in future''' iftype(data) isnotdict: # we're only going to test for dicts for now raise ValueError('only dicts are supported for now')
from collections import OrderedDict try: foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])) except ValueError as e: print(e) # 'only dicts are supported for now'
isinstance() 示例
1 2 3 4 5 6 7 8
deffoo(a_dict): ifnotisinstance(a_dict, dict): raise ValueError('argument must be a dict') return a_dict
from collections import OrderedDict result = foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])) print(result) # OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])
使用抽象基类
1 2 3 4 5 6 7
from collections import Mapping
deffoo(a_dict): ifnotisinstance(a_dict, Mapping): raise ValueError('argument must be a dict') return a_dict