Shouldn’t this go to itertools-ideas? :-) On Mon, Jul 27, 2020 at 13:56 David Mertz <[email protected]> wrote:
> I don't like consuming the iterator in the exception case. You might > expect just one, but have a fallback approach for more. You could build the > safer behavior using itertools.tee() or itertools.chain(). > > On Mon, Jul 27, 2020, 3:10 PM Noam Yorav-Raphael <[email protected]> > wrote: > >> Hi, >> >> There's a simple function that I use many times, and I think may be a >> good fit to be added to itertools. A function that gets an iterator, and if >> it has exactly one element returns it, and otherwise raises an exception. >> This is very useful for cases where I do some sort of query that I expect >> to get exactly one result, and I want an exception to be raised if I'm >> wrong. For example: >> >> jack = one(p for p in people if p.id == '1234') >> >> sqlalchemy already has such a function for queries: >> https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.one >> >> This is my implementation: >> >> def one(iterable): >> it = iter(iterable) >> try: >> r = next(it) >> except StopIteration: >> raise ValueError("Iterator is empty") >> try: >> next(it) >> except StopIteration: >> return r >> else: >> raise ValueError("Iterator has more than one item") >> >> What do you think? >> >> Thanks, >> Noam >> _______________________________________________ >> Python-Dev mailing list -- [email protected] >> To unsubscribe send an email to [email protected] >> https://mail.python.org/mailman3/lists/python-dev.python.org/ >> Message archived at >> https://mail.python.org/archives/list/[email protected]/message/D52MPKLIN4VEXBOCKVMTWAK66MAOEINY/ >> Code of Conduct: http://python.org/psf/codeofconduct/ >> > _______________________________________________ > Python-Dev mailing list -- [email protected] > To unsubscribe send an email to [email protected] > https://mail.python.org/mailman3/lists/python-dev.python.org/ > Message archived at > https://mail.python.org/archives/list/[email protected]/message/N75BG5XVXKENVWAPU4K5UP4I3DKXTITO/ > Code of Conduct: http://python.org/psf/codeofconduct/ > -- --Guido (mobile)
_______________________________________________ Python-Dev mailing list -- [email protected] To unsubscribe send an email to [email protected] https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/[email protected]/message/IMED3FXEGFYJJX7KCWQLYO7SPNJAO2MS/ Code of Conduct: http://python.org/psf/codeofconduct/
