Path: csiph.com!usenet.pasdenom.info!gegeweb.org!usenet-fr.net!nerim.net!novso.com!newsfeed.xs4all.nl!newsfeed6.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'argument': 0.04; 'exception.': 0.07; 'suppose': 0.07; 'try:': 0.07; 'called.': 0.09; 'defined.': 0.09; 'exception:': 0.09; 'function:': 0.09; 'here?': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.10; 'possible?': 0.16; 'received:80.91.229.3': 0.16; 'received:dip.t-dialin.net': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-dialin.net': 0.16; 'subject:arithmetic': 0.16; 'wrote:': 0.17; '>>>': 0.18; 'define': 0.20; 'header:User- Agent:1': 0.26; 'header:X-Complaints-To:1': 0.28; 'prints': 0.29; 'evaluation': 0.30; 'function': 0.30; 'could': 0.32; 'print': 0.32; 'like:': 0.33; 'to:addr:python-list': 0.33; 'something': 0.35; 'there': 0.35; 'received:org': 0.36; 'except': 0.36; 'passed': 0.37; 'subject:: ': 0.38; 'mark': 0.38; 'to:addr:python.org': 0.39; 'header:Received:5': 0.40; 'chance': 0.61; 'therefore': 0.65; '666': 0.84 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Peter Otten <__peter__@web.de> Subject: Re: Guarding arithmetic Date: Thu, 23 Aug 2012 12:11:21 +0200 Organization: None References: <8b9a5844-66b0-4940-946a-5e626462cdce@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Gmane-NNTP-Posting-Host: p50848ff6.dip.t-dialin.net User-Agent: KNode/4.7.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.12 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 30 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1345716686 news.xs4all.nl 6955 [2001:888:2000:d::a6]:57811 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:27721 Mark Carter wrote: > Suppose I want to define a function "safe", which returns the argument > passed if there is no error, and 42 if there is one. So the setup is > something like: > > def safe(x): > # WHAT WOULD DEFINE HERE? > > print safe(666) # prints 666 > print safe(1/0) # prints 42 > > I don't see how such a function could be defined. Is it possible? 1/0 is evaluated before safe() is called. Therefore safe() has no chance to catch the exception. You have to move the evaluation into the safe() function: >>> def safe(deferred, default=42, exception=Exception): ... try: ... return deferred() ... except exception: ... return default ... >>> print safe(lambda: 666) 666 >>> print safe(lambda: 1/0) 42