Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20204 > unrolled thread

Re: Postpone evaluation of argument

Started byChris Rebert <clp2@rebertia.com>
First post2012-02-10 15:12 -0800
Last post2012-02-10 15:12 -0800
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Postpone evaluation of argument Chris Rebert <clp2@rebertia.com> - 2012-02-10 15:12 -0800

#20204 — Re: Postpone evaluation of argument

FromChris Rebert <clp2@rebertia.com>
Date2012-02-10 15:12 -0800
SubjectRe: Postpone evaluation of argument
Message-ID<mailman.5687.1328915560.27778.python-list@python.org>
On Fri, Feb 10, 2012 at 3:01 PM, Righard van Roy <pluijzer@gmail.com> wrote:
> 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.

Nope. All arguments always get evaluated before control passes to the
callee. You'd have to "quote" the arguments manually by putting them
in lambdas, thus explicitly delaying their evaluation.

Cheers,
Chris
--
http://rebertia.com

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web