我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用collections.UserDict()。
def objdict(orig): return UserDict(orig) #class objdict(dict): # def __init__(self,initial={}): # for k,v in initial.items(): # self[k] = v # # def __getattr__(self, name): # if name in self: # return self[name] # else: # raise AttributeError("No such attribute: " + name) # # def __setattr__(self, name, value): # self[name] = value # # def __delattr__(self, name): # if name in self: # del self[name] # else: # raise AttributeError("No such attribute: " + name)
def test_MutableMapping_subclass(self): # Test issue 9214 mymap = UserDict() mymap['red'] = 5 self.assertIsInstance(mymap.keys(), Set) self.assertIsInstance(mymap.keys(), KeysView) self.assertIsInstance(mymap.items(), Set) self.assertIsInstance(mymap.items(), ItemsView) mymap = UserDict() mymap['red'] = 5 z = mymap.keys() | {'orange'} self.assertIsInstance(z, set) list(z) mymap['blue'] = 7 # Shouldn't affect 'z' self.assertEqual(sorted(z), ['orange', 'red']) mymap = UserDict() mymap['red'] = 5 z = mymap.items() | {('orange', 3)} self.assertIsInstance(z, set) list(z) mymap['blue'] = 7 # Shouldn't affect 'z' self.assertEqual(sorted(z), [('orange', 3), ('red', 5)])
def test_plain(self): f = self.makeCallable('a, b=1') self.assertEqualCallArgs(f, '2') self.assertEqualCallArgs(f, '2, 3') self.assertEqualCallArgs(f, 'a=2') self.assertEqualCallArgs(f, 'b=3, a=2') self.assertEqualCallArgs(f, '2, b=3') # expand *iterable / **mapping self.assertEqualCallArgs(f, '*(2,)') self.assertEqualCallArgs(f, '*[2]') self.assertEqualCallArgs(f, '*(2, 3)') self.assertEqualCallArgs(f, '*[2, 3]') self.assertEqualCallArgs(f, '**{"a":2}') self.assertEqualCallArgs(f, 'b=3, **{"a":2}') self.assertEqualCallArgs(f, '2, **{"b":3}') self.assertEqualCallArgs(f, '**{"b":3, "a":2}') # expand UserList / UserDict self.assertEqualCallArgs(f, '*collections.UserList([2])') self.assertEqualCallArgs(f, '*collections.UserList([2, 3])') self.assertEqualCallArgs(f, '**collections.UserDict(a=2)') self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)') self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)')
def test_multiple_features(self): f = self.makeCallable('a, b=2, *f, **g') self.assertEqualCallArgs(f, '2, 3, 7') self.assertEqualCallArgs(f, '2, 3, x=8') self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9') self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9') self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' '[2, 3, (4,[5,6])]), **{"y":9, "z":10}') self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' '(4,[5,6])]), **collections.UserDict(' 'y=9, z=10)') f = self.makeCallable('a, b=2, *f, x, y=99, **g') self.assertEqualCallArgs(f, '2, 3, x=8') self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10') self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10') self.assertEqualCallArgs(f, 'x=8, *collections.UserList(' '[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}') self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, ' '(4,[5,6])]), q=0, **collections.UserDict(' 'y=9, z=10)')
def test_redirects_to_https_with_port_number(self): # same thing, but with :443 on the URL, see issue #180 self.reqs['responses']['http'].url = 'https://http-observatory.security.mozilla.org:443/' history1 = UserDict() history1.request = UserDict() history1.request.url = 'http://http-observatory.security.mozilla.org/' self.reqs['responses']['http'].history.append(history1) result = redirection(self.reqs) self.assertEquals('redirection-to-https', result['result']) self.assertEquals(['http://http-observatory.security.mozilla.org/', 'https://http-observatory.security.mozilla.org:443/'], result['route']) self.assertTrue(result['pass'])
def test_all_redirections_preloaded(self): self.reqs['responses']['http'].url = 'https://www.pokeinthe.io/foo/bar' for url in ('http://pokeinthe.io/', 'https://pokeinthe.io/', 'https://www.pokeinthe.io/', 'https://baz.pokeinthe.io/foo'): history = UserDict() history.request = UserDict() history.request.url = url self.reqs['responses']['http'].history.append(history) result = redirection(self.reqs) self.assertEquals('redirection-all-redirects-preloaded', result['result']) self.assertTrue(result['pass'])
def test_compat_pickle(self): tests = [ (range(1, 7), '__builtin__', 'xrange'), (map(int, '123'), 'itertools', 'imap'), (functools.reduce, '__builtin__', 'reduce'), (dbm.whichdb, 'whichdb', 'whichdb'), (Exception(), 'exceptions', 'Exception'), (collections.UserDict(), 'UserDict', 'IterableUserDict'), (collections.UserList(), 'UserList', 'UserList'), (collections.defaultdict(), 'collections', 'defaultdict'), ] for val, mod, name in tests: for proto in range(3): with self.subTest(type=type(val), proto=proto): pickled = self.dumps(val, proto) self.assertIn(('c%s\n%s' % (mod, name)).encode(), pickled) self.assertIs(type(self.loads(pickled)), type(val))
def __init__(*args, **kwargs): if not args: raise TypeError("descriptor '__init__' of 'UserDict' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) if args: dict_ = args[0] elif 'dict' in kwargs: dict_ = kwargs.pop('dict') import warnings warnings.warn("Passing 'dict' as keyword argument is deprecated", DeprecationWarning, stacklevel=2) else: dict_ = None self.data = {} if dict_ is not None: self.data.update(dict_) if len(kwargs): self.data.update(kwargs)
def test_fromkeys(self): TestMappingProtocol.test_fromkeys(self) class mydict(self.type2test): def __new__(cls): return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) self.assertIsInstance(ud, collections.UserDict)
def _unwrap(obj): if isinstance(obj, UserList) or isinstance(obj, UserDict): return obj.data return obj
def test_varkw(self): f = self.makeCallable('a, b=1, **c') self.assertEqualCallArgs(f, 'a=2') self.assertEqualCallArgs(f, '2, b=3, c=4') self.assertEqualCallArgs(f, 'b=3, a=2, c=4') self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}') self.assertEqualCallArgs(f, '2, c=4, **{"b":3}') self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}') self.assertEqualCallArgs(f, '**collections.UserDict(a=2, b=3, c=4)') self.assertEqualCallArgs(f, '2, c=4, **collections.UserDict(b=3)') self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3, c=4)')
def test_varkw_only(self): # issue11256: f = self.makeCallable('**c') self.assertEqualCallArgs(f, '') self.assertEqualCallArgs(f, 'a=1') self.assertEqualCallArgs(f, 'a=1, b=2') self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}') self.assertEqualCallArgs(f, '**collections.UserDict(a=1, b=2)') self.assertEqualCallArgs(f, 'c=3, **collections.UserDict(a=1, b=2)')
def test_redirection_not_to_https(self): self.reqs['responses']['http'].url = 'http://http-observatory.security.mozilla.org/foo' history1 = UserDict() history1.request = UserDict() history1.request.url = 'http://http-observatory.security.mozilla.org/' self.reqs['responses']['http'].history.append(history1) result = redirection(self.reqs) self.assertEquals('redirection-not-to-https', result['result']) self.assertFalse(result['pass'])
def test_redirects_to_https(self): # normal redirect to https history1 = UserDict() history1.request = UserDict() history1.request.url = 'http://http-observatory.security.mozilla.org/' self.reqs['responses']['http'].history.append(history1) result = redirection(self.reqs) self.assertEquals('redirection-to-https', result['result']) self.assertEquals(['http://http-observatory.security.mozilla.org/', 'https://http-observatory.security.mozilla.org/'], result['route']) self.assertTrue(result['pass'])
def test_redirects_invalid_cert(self): history1 = UserDict() history1.request = UserDict() history1.request.url = 'http://http-observatory.security.mozilla.org/' self.reqs['responses']['http'].history.append(history1) # Mark it as verification failed self.reqs['responses']['http'].verified = False result = redirection(self.reqs) self.assertEquals('redirection-invalid-cert', result['result']) self.assertFalse(result['pass'])
def test_first_redirection_off_host(self): self.reqs['responses']['http'].url = 'https://http-foo.services.mozilla.com/' history1 = UserDict() history1.status_code = 301 history1.request = UserDict() history1.request.url = 'http://http-observatory.security.mozilla.org/' self.reqs['responses']['http'].history.append(history1) result = redirection(self.reqs) self.assertEquals('redirection-off-host-from-http', result['result']) self.assertFalse(result['pass'])
def __init__(self, *args, equal=None, tracker=None, **kwargs): self._key_dependencies = {} ReactiveContainerBase.__init__(self, equal, tracker=tracker) collections.UserDict.__init__(self, *args, **kwargs)
def __init__(self, dict): collections.UserDict.__init__(self, dict) if SCons.Debug.track_instances: logInstanceCreation(self, 'Builder.OverrideWarner') self.already_warned = None
def __init__(self, *args, **kwargs): collections.UserDict.__init__(self, *args, **kwargs) # draw the sprites in the dict
def update_dict(self, *args, **kwargs): collections.UserDict.update(self, *args, **kwargs)
def test_compat_unpickle(self): # xrange(1, 7) pickled = b'\x80\x02c__builtin__\nxrange\nK\x01K\x07K\x01\x87R.' unpickled = self.loads(pickled) self.assertIs(type(unpickled), range) self.assertEqual(unpickled, range(1, 7)) self.assertEqual(list(unpickled), [1, 2, 3, 4, 5, 6]) # reduce pickled = b'\x80\x02c__builtin__\nreduce\n.' self.assertIs(self.loads(pickled), functools.reduce) # whichdb.whichdb pickled = b'\x80\x02cwhichdb\nwhichdb\n.' self.assertIs(self.loads(pickled), dbm.whichdb) # Exception(), StandardError() for name in (b'Exception', b'StandardError'): pickled = (b'\x80\x02cexceptions\n' + name + b'\nU\x03ugh\x85R.') unpickled = self.loads(pickled) self.assertIs(type(unpickled), Exception) self.assertEqual(str(unpickled), 'ugh') # UserDict.UserDict({1: 2}), UserDict.IterableUserDict({1: 2}) for name in (b'UserDict', b'IterableUserDict'): pickled = (b'\x80\x02(cUserDict\n' + name + b'\no}U\x04data}K\x01K\x02ssb.') unpickled = self.loads(pickled) self.assertIs(type(unpickled), collections.UserDict) self.assertEqual(unpickled, collections.UserDict({1: 2}))
def test_init(self): for kw in 'self', 'other', 'iterable': self.assertEqual(list(collections.UserDict(**{kw: 42}).items()), [(kw, 42)]) self.assertEqual(list(collections.UserDict({}, dict=42).items()), [('dict', 42)]) self.assertEqual(list(collections.UserDict({}, dict=None).items()), [('dict', None)]) with self.assertWarnsRegex(PendingDeprecationWarning, "'dict'"): self.assertEqual(list(collections.UserDict(dict={'a': 42}).items()), [('a', 42)]) self.assertRaises(TypeError, collections.UserDict, 42) self.assertRaises(TypeError, collections.UserDict, (), ()) self.assertRaises(TypeError, collections.UserDict.__init__)
def test_setting_dict_to_invalid(self): self.cannot_set_attr(self.b, '__dict__', None, TypeError) from collections import UserDict d = UserDict({'known_attr': 7}) self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
def dump(self): """Return the JSON representaion of config.""" import json def _json_default(v): # How to encode non-standard objects if isinstance(v, UserDict): return v.data else: return str(v) # Work on copy of CONFIG but with unused top-level elements removed. # config = {k: v for k,v in self.items() if v} return json.dumps(config, indent=INDENT, sort_keys=SORT, default=_json_default)
def test_dotty_type(self): # self.assertIsInstance(self.dotty, dict) self.assertIsInstance(self.dotty, Mapping) self.assertIsInstance(self.dotty, UserDict) self.assertIsInstance(self.dotty, Dotty)
def test_work_with_not_dotty_dict_like_objects(self): # Assume dict-like objects does not support dot notation self.dotty['already.exist.custom'] = UserDict({ 'not_dotty': { 'user_dict': 'I am deeply nested user dict value' } }) # Accessing not existing key from dict-like object should raise KeyError self.assertRaises(KeyError, self.dotty['already.exist.custom.key_value']) # One can access not Dotty dict-like object with dot notation self.assertEqual(self.dotty['already.exist.custom.not_dotty.user_dict'], 'I am deeply nested user dict value') # one can add new key to not dotty dict-like object with dot notation self.dotty['already.exist.custom.not_dotty.new_key'] = 'new key inside not dotty dict' self.assertEqual( self.dotty['already.exist.custom'], { 'not_dotty': { 'user_dict': 'I am deeply nested user dict value', 'new_key': 'new key inside not dotty dict', } } )
def test_fromkeys(self): self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = self._empty_mapping() self.assertTrue(not(d.fromkeys('abc') is d)) self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) self.assertEqual(d.fromkeys([]), {}) def g(): yield 1 self.assertEqual(d.fromkeys(g()), {1:None}) self.assertRaises(TypeError, {}.fromkeys, 3) class dictlike(self.type2test): pass self.assertEqual(dictlike.fromkeys('a'), {'a':None}) self.assertEqual(dictlike().fromkeys('a'), {'a':None}) self.assertTrue(dictlike.fromkeys('a').__class__ is dictlike) self.assertTrue(dictlike().fromkeys('a').__class__ is dictlike) self.assertTrue(type(dictlike.fromkeys('a')) is dictlike) class mydict(self.type2test): def __new__(cls): return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) self.assertIsInstance(ud, collections.UserDict) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass class baddict1(self.type2test): def __init__(self): raise Exc() self.assertRaises(Exc, baddict1.fromkeys, [1]) class BadSeq(object): def __iter__(self): return self def __next__(self): raise Exc() self.assertRaises(Exc, self.type2test.fromkeys, BadSeq()) class baddict2(self.type2test): def __setitem__(self, key, value): raise Exc() self.assertRaises(Exc, baddict2.fromkeys, [1])
def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} self.assertIsNot(d.fromkeys('abc'), d) self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) self.assertEqual(d.fromkeys([]), {}) def g(): yield 1 self.assertEqual(d.fromkeys(g()), {1:None}) self.assertRaises(TypeError, {}.fromkeys, 3) class dictlike(dict): pass self.assertEqual(dictlike.fromkeys('a'), {'a':None}) self.assertEqual(dictlike().fromkeys('a'), {'a':None}) self.assertIsInstance(dictlike.fromkeys('a'), dictlike) self.assertIsInstance(dictlike().fromkeys('a'), dictlike) class mydict(dict): def __new__(cls): return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) self.assertIsInstance(ud, collections.UserDict) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass class baddict1(dict): def __init__(self): raise Exc() self.assertRaises(Exc, baddict1.fromkeys, [1]) class BadSeq(object): def __iter__(self): return self def __next__(self): raise Exc() self.assertRaises(Exc, dict.fromkeys, BadSeq()) class baddict2(dict): def __setitem__(self, key, value): raise Exc() self.assertRaises(Exc, baddict2.fromkeys, [1]) # test fast path for dictionary inputs d = dict(zip(range(6), range(6))) self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6)))
def test_missing(self): # Make sure UserDict doesn't have a __missing__ method self.assertEqual(hasattr(collections.UserDict, "__missing__"), False) # Test several cases: # (D) subclass defines __missing__ method returning a value # (E) subclass defines __missing__ method raising RuntimeError # (F) subclass sets __missing__ instance variable (no effect) # (G) subclass doesn't define __missing__ at a all class D(collections.UserDict): def __missing__(self, key): return 42 d = D({1: 2, 3: 4}) self.assertEqual(d[1], 2) self.assertEqual(d[3], 4) self.assertNotIn(2, d) self.assertNotIn(2, d.keys()) self.assertEqual(d[2], 42) class E(collections.UserDict): def __missing__(self, key): raise RuntimeError(key) e = E() try: e[42] except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail("e[42] didn't raise RuntimeError") class F(collections.UserDict): def __init__(self): # An instance variable __missing__ should have no effect self.__missing__ = lambda key: None collections.UserDict.__init__(self) f = F() try: f[42] except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail("f[42] didn't raise KeyError") class G(collections.UserDict): pass g = G() try: g[42] except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail("g[42] didn't raise KeyError")