[Python-ideas] get method for sets?

Mike Meyer mwm at mired.org
Thu May 17 05:49:01 CEST 2012


On Thu, 17 May 2012 15:03:11 +1200
Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> On 17/05/12 14:19, Paul Du Bois wrote:
> > On Wed, May 16, 2012 at 5:56 PM, Cameron Simpson <cs at zip.com.au> wrote:
> >> >  def an(s):
> >> >    for i in s:
> >> >      return i
> > Normally I'm content to lurk, but this thread has been going on for a
> > long time without anyone pointing out that the "for" loop idiom needs
> > an "else: raise KeyError" in order to act pythonically.
> That depends on what result you want in the empty set case. If
> returning None is okay, or you know the set can never be empty,
> then it's fine as written.

Raising KeyError is probably best, as that parallels "pop". In fact,
it would be required for the proposed "peek" method that returns what
"pop" would have returned at that point.

That method would not only have satisfied all 2.5 of the use cases I
had, but would probably be useful for algorithms that want a
conditional pop.

	    <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/
Independent Software developer/SCM consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list