Postpone evaluation of argument
Righard van Roy
pluijzer at gmail.com
Fri Feb 10 18:01:52 EST 2012
Hello,
I want to add an item to a list, except if the evaluation of that item
results in an exception.
I could do that like this:
def r(x):
if x > 3:
raise(ValueError)
try:
list.append(r(1))
except:
pass
try:
list.append(r(5))
except:
pass
This looks rather clumbsy though, and it does not work with i.e. list
comprehensions.
I was thinking of writing a decorator like this:
def tryAppendDecorator(fn):
def new(*args):
try:
fn(*args)
except:
pass
return new
@tryAppendDecorator
def tryAppend(list, item):
list.append(item)
tryAppend(list, r(1))
tryAppend(list, r(5))
This does not work however because the 'item' argument gets evaluated
before the decorator does it's magic.
Is there a way to postpone the evaluation of 'item' till it gets used
inside the decorator. Like it is possible to quote a form in Lisp.
Thank you,
Righard
More information about the Python-list
mailing list