Re: Postpone evaluation of argument



Righard van Roy <pluijzer@xxxxxxxxx> writes:
I want to add an item to a list, except if the evaluation of that item
results in an exception.

This may be overkill and probably slow, but perhaps most in the spirit
that you're asking.

from itertools import chain

def r(x):
if x > 3:
raise(ValueError)
return x

def maybe(func):
try:
yield func()
except:
return

def p(i): return maybe(lambda: r(i))

your_list = list(chain(p(1), p(5)))
print your_list
.



Relevant Pages

  • Re: Break up list into groups
    ... def splitIntoGroups: ... Here's an ugly way I wouldn't recommended (using itertools groupby): ... James Stroud ...
    (comp.lang.python)
  • whats the only one obvious way?
    ... The question is when we are expected to use itertools and when we ... def all: ... seq) ... It seems to me that list comprehensions won; also Guido publicly said ...
    (comp.lang.python)
  • Re: loop over list and process into groups
    ... I was going to write a def to loop through and look for certain pre- ... I thought about using itertools, but i only use that for fixed data. ... I don't know of a good way to loop over variably sized data. ... Good use of groupby. ...
    (comp.lang.python)
  • Re: Recursive generator
    ...     def genDescendents: ... "Descendant" is basically French. ... Often generators can be written more concisely with itertools at the ... def genDescendants: ...
    (comp.lang.python)
  • Re: getting n items at a time from a generator
    ... from itertools import * ... def group: ... iters = tee ... Kugutsumen> list version since I need to buffer that chunk in memory at ...
    (comp.lang.python)