Lie Ryan wrote: > On 1/5/2010 1:31 PM, r0g wrote: >> Michi wrote: >>> On Jan 4, 1:30 pm, Steven D'Aprano >>> <ste...@remove.this.cybersource.com.au> wrote: <snip> >> A pattern I have used a few times is that of returning an explicit >> success/failure code alongside whatever the function normally returns. >> While subsequent programmers might not intuit the need to test for >> (implicit) "magic" return values they ought to notice if they start >> getting tuples back where they expected scalars... >> >> def foo(x) >> if x>0: >> return True, x*x >> else: >> return False, "Bad value of x in foo:",str(x) >> >> ok, value = foo(-1) >> if ok: >> print "foo of x is", value >> else: >> print "ERROR:", value > > Except that that is a reinvention of try-wheel: >
True, but there's more than one way to skin a cat! Mine's faster if you expect a high rate of failures (over 15%). > def foo(x): > if x > 0: > return x*x > else: > raise MathError("Bad value of x in foo: %s" % x) > > try: > print foo(-1) > except MathError, e: > print "ERROR: System integrity is doubted" > > or rather; that is perhaps a good example of when to use 'assert'. If > the domain of foo() is positive integers, calling -1 on foo is a bug in > the caller, not foo(). Maybe, although I recently learned on here that one can't rely on assert statements in production code, their intended use is to aid debugging and testing really. Besides, that was just a toy example. > > I have been looking at Haskell recently and the way the pure functional > language handled exceptions and I/O gives me a new distinct "insight" > that exceptions can be thought of as a special return value that is > implicitly wrapped and unwrapped up the call stack until it is > explicitly handled. Yes there's some very interesting paradigms coming out of functional programming but, unless you're a maths major, functional languages are a long way off being productivity tools! Elegant: yes, provable: maybe, practical for everyday coding: not by a long shot! Roger. -- http://mail.python.org/mailman/listinfo/python-list