我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用collections.abc.Iterator()。
def test_Iterator(self): non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()] for x in non_samples: self.assertNotIsInstance(x, Iterator) self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) samples = [iter(bytes()), iter(str()), iter(tuple()), iter(list()), iter(dict()), iter(set()), iter(frozenset()), iter(dict().keys()), iter(dict().items()), iter(dict().values()), (lambda: (yield))(), (x for x in []), ] for x in samples: self.assertIsInstance(x, Iterator) self.assertTrue(issubclass(type(x), Iterator), repr(type(x))) self.validate_abstract_methods(Iterator, '__next__', '__iter__') # Issue 10565 class NextOnly: def __next__(self): yield 1 raise StopIteration self.assertNotIsInstance(NextOnly(), Iterator)
def test_construct(self): def _check_iterator(it): self.assertIsInstance(it, abc.Iterator) self.assertIsInstance(it, abc.Iterable) s = struct.Struct('>ibcp') it = s.iter_unpack(b"") _check_iterator(it) it = s.iter_unpack(b"1234567") _check_iterator(it) # Wrong bytes length with self.assertRaises(struct.error): s.iter_unpack(b"123456") with self.assertRaises(struct.error): s.iter_unpack(b"12345678") # Zero-length struct s = struct.Struct('>') with self.assertRaises(struct.error): s.iter_unpack(b"") with self.assertRaises(struct.error): s.iter_unpack(b"12")
def test_direct_subclassing(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C(B): pass self.assertTrue(issubclass(C, B)) self.assertFalse(issubclass(int, C))
def test_registration(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C: __hash__ = None # Make sure it isn't hashable by default self.assertFalse(issubclass(C, B), B.__name__) B.register(C) self.assertTrue(issubclass(C, B))
def __reversed__(self) -> 'Iterator[T_co]': pass
def dumps(obj): if isinstance(obj, Iterator): obj = list(obj) return json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False)
def __reversed__(self) -> 'Iterator[T]': pass
def print_json(obj, verbose=False, err=False): def default(obj): if hasattr(obj, 'for_json'): if 'verbose' in signature(obj.for_json).parameters: return obj.for_json(verbose=verbose) else: return obj.for_json() elif isinstance(obj, Iterator): return list(obj) else: try: data = vars(obj).copy() except TypeError: data = {"__repr__": repr(obj)} data["__class__"] = type(obj).__name__ return data def dumps(x): return json.dumps(x, sort_keys=True, indent=4, ensure_ascii=False, default=default) if isinstance(obj, Iterator): first = True click.echo('[', nl=False, err=err) for o in obj: if first: click.echo(err=err) first = False else: click.echo(',', err=err) click.echo(indent(dumps(o), ' '*4), nl=False, err=err) if not first: click.echo(err=err) click.echo(']', err=err) else: click.echo(dumps(obj), err=err)
def mk_gen(): from abc import abstractmethod required_methods = ( '__iter__', '__next__' if hasattr(iter(()), '__next__') else 'next', 'send', 'throw', 'close') class Generator(_collections_abc.Iterator): __slots__ = () if '__next__' in required_methods: def __next__(self): return self.send(None) else: def next(self): return self.send(None) @abstractmethod def send(self, value): raise StopIteration @abstractmethod def throw(self, typ, val=None, tb=None): if val is None: if tb is None: raise typ val = typ() if tb is not None: val = val.with_traceback(tb) raise val def close(self): try: self.throw(GeneratorExit) except (GeneratorExit, StopIteration): pass else: raise RuntimeError('generator ignored GeneratorExit') @classmethod def __subclasshook__(cls, C): if cls is Generator: mro = C.__mro__ for method in required_methods: for base in mro: if method in base.__dict__: break else: return NotImplemented return True return NotImplemented generator = type((lambda: (yield))()) Generator.register(generator) return Generator