我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用collections.UserList()。
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_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 __reduce_ex__(self, *args, **kwargs): # The `list` reduce function returns an iterator as the fourth element # that is normally used for repopulating. Since we only inherit from # `list` for `isinstance` backward compatibility (Refs #17413) we # nullify this iterator as it would otherwise result in duplicate # entries. (Refs #23594) info = super(UserList, self).__reduce_ex__(*args, **kwargs) return info[:3] + (None, None) # Utilities for time zone support in DateTimeField et al.
def _unwrap(obj): if isinstance(obj, UserList) or isinstance(obj, UserDict): return obj.data return obj
def test_join(self): # join now works with any sequence type # moved here, because the argument order is # different in string.join (see the test in # test.test_string.StringTest.test_join) self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd')) self.checkequal('bd', '', 'join', ('', 'b', '', 'd')) self.checkequal('ac', '', 'join', ('a', '', 'c', '')) self.checkequal('w x y z', ' ', 'join', Sequence()) self.checkequal('abc', 'a', 'join', ('abc',)) self.checkequal('z', 'a', 'join', UserList(['z'])) self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c']) self.assertRaises(TypeError, '.'.join, ['a', 'b', 3]) for i in [5, 25, 125]: self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ['a' * i] * i) self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ('a' * i,) * i) #self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1()) self.checkequal('a b c', ' ', 'join', BadSeq2()) self.checkraises(TypeError, ' ', 'join') self.checkraises(TypeError, ' ', 'join', 7) self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()]) try: def f(): yield 4 + "" self.fixtype(' ').join(f()) except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: self.fail('exception not raised')
def test_basic_proxy(self): o = C() self.check_proxy(o, weakref.proxy(o)) L = collections.UserList() p = weakref.proxy(L) self.assertFalse(p, "proxy for empty UserList should be false") p.append(12) self.assertEqual(len(L), 1) self.assertTrue(p, "proxy for non-empty UserList should be true") p[:] = [2, 3] self.assertEqual(len(L), 2) self.assertEqual(len(p), 2) self.assertIn(3, p, "proxy didn't support __contains__() properly") p[1] = 5 self.assertEqual(L[1], 5) self.assertEqual(p[1], 5) L2 = collections.UserList(L) p2 = weakref.proxy(L2) self.assertEqual(p, p2) ## self.assertEqual(repr(L2), repr(p2)) L3 = collections.UserList(range(10)) p3 = weakref.proxy(L3) self.assertEqual(L3[:], p3[:]) self.assertEqual(L3[5:], p3[5:]) self.assertEqual(L3[:5], p3[:5]) self.assertEqual(L3[2:5], p3[2:5])
def test_add_specials(self): u = UserList("spam") u2 = u + "eggs" self.assertEqual(u2, list("spameggs"))
def test_radd_specials(self): u = UserList("eggs") u2 = "spam" + u self.assertEqual(u2, list("spameggs")) u2 = u.__radd__(UserList("spam")) self.assertEqual(u2, list("spameggs"))
def test_iadd(self): super().test_iadd() u = [0, 1] u += UserList([0, 1]) self.assertEqual(u, [0, 1, 0, 1])
def testWritelinesUserList(self): # verify writelines with instance sequence l = UserList([b'1', b'2']) self.f.writelines(l) self.f.close() self.f = self.open(TESTFN, 'rb') buf = self.f.read() self.assertEqual(buf, b'12')
def testWritelinesIntegersUserList(self): # verify writelines with integers in UserList l = UserList([1,2,3]) self.assertRaises(TypeError, self.f.writelines, l)
def test_precomputed(self): for func, data, elem, expected in self.precomputedCases: self.assertEqual(func(data, elem), expected) self.assertEqual(func(UserList(data), elem), expected)
def test_vsBuiltinSort(self, n=500): from random import choice for insorted in (list(), UserList()): for i in range(n): digit = choice("0123456789") if digit in "02468": f = self.module.insort_left else: f = self.module.insort_right f(insorted, digit) self.assertEqual(sorted(insorted), insorted)
def test_collections_userstuff(self): """ UserDict, UserList, and UserString have been moved to the collections module. """ from collections import UserDict from collections import UserList from collections import UserString self.assertTrue(True)
def test_install_aliases(self): """ Does the install_aliases() interface monkey-patch urllib etc. successfully? """ from future.standard_library import remove_hooks, install_aliases remove_hooks() install_aliases() from collections import Counter, OrderedDict # backported to Py2.6 from collections import UserDict, UserList, UserString # Requires Python dbm support: # import dbm # import dbm.dumb # import dbm.gnu # import dbm.ndbm from itertools import filterfalse, zip_longest from subprocess import check_output # backported to Py2.6 from subprocess import getoutput, getstatusoutput from sys import intern # test_support may not be available (e.g. on Anaconda Py2.6): # import test.support import urllib.error import urllib.parse import urllib.request import urllib.response import urllib.robotparser self.assertTrue('urlopen' in dir(urllib.request))
def test_UserList(self): before = """ from UserList import UserList a = UserList([1, 3, 5]) assert len(a) == 3 """ after = """ from collections import UserList a = UserList([1, 3, 5]) assert len(a) == 3 """ self.convert_check(before, after, stages=(1, 2), ignore_imports=True)
def __init__(self, initlist=[], allowedElems=[]): collections.UserList.__init__(self, [_f for _f in initlist if _f]) self.allowedElems = sorted(allowedElems)
def test_writelines_userlist(self): l = UserList([b'ab', b'cd', b'ef']) writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.writelines(l) bufio.flush() self.assertEqual(b''.join(writer._write_stack), b'abcdef')
def test_writelines_userlist(self): l = UserList(['ab', 'cd', 'ef']) buf = self.BytesIO() txt = self.TextIOWrapper(buf) txt.writelines(l) txt.flush() self.assertEqual(buf.getvalue(), b'abcdef')
def test_recursion(self): # Check that comparison for recursive objects fails gracefully from collections import UserList a = UserList() b = UserList() a.append(b) b.append(a) self.assertRaises(RuntimeError, operator.eq, a, b) self.assertRaises(RuntimeError, operator.ne, a, b) self.assertRaises(RuntimeError, operator.lt, a, b) self.assertRaises(RuntimeError, operator.le, a, b) self.assertRaises(RuntimeError, operator.gt, a, b) self.assertRaises(RuntimeError, operator.ge, a, b) b.append(17) # Even recursive lists of different lengths are different, # but they cannot be ordered self.assertTrue(not (a == b)) self.assertTrue(a != b) self.assertRaises(RuntimeError, operator.lt, a, b) self.assertRaises(RuntimeError, operator.le, a, b) self.assertRaises(RuntimeError, operator.gt, a, b) self.assertRaises(RuntimeError, operator.ge, a, b) a.append(17) self.assertRaises(RuntimeError, operator.eq, a, b) self.assertRaises(RuntimeError, operator.ne, a, b) a.insert(0, 11) b.insert(0, 12) self.assertTrue(not (a == b)) self.assertTrue(a != b) self.assertTrue(a < b)
def testWritelinesUserList(self): l = UserList([b'123', b'456']) self.f.writelines(l) self.f.close() self.f = _FileIO(TESTFN, 'rb') buf = self.f.read() self.assertEqual(buf, b'123456')
def test_varargs(self): f = self.makeCallable('a, b=1, *c') self.assertEqualCallArgs(f, '2') self.assertEqualCallArgs(f, '2, 3') self.assertEqualCallArgs(f, '2, 3, 4') self.assertEqualCallArgs(f, '*(2,3,4)') self.assertEqualCallArgs(f, '2, *[3,4]') self.assertEqualCallArgs(f, '2, 3, *collections.UserList([4])')