[Python-Dev] PEP 8 update (original) (raw)

Steven D'Aprano steve at pearwood.info
Wed Apr 8 04:16:14 CEST 2015


On Tue, Apr 07, 2015 at 08:47:25AM -0400, Ben Hoyt wrote:

> My own preference would be: > > def foo(x): > if x >= 0: > return math.sqrt(x) > return None

Kind of getting into the weeds here, but I would always invert this to "return errors early, and keep the normal flow at the main indentation level". Depends a little on what foo() means, but it seems to me the "return None" case is the exceptional/error case, so this would be: def foo(x): if x < 0: return None return math.sqrt(x)

While in general I agree with "handle the error case early", there are cases where "handle the normal case early" is better, and I think that this is one of them. Also, inverting the comparison isn't appropriate, due to float NANs. With the first version, foo(NAN) returns None (which I assumed was deliberate by the OP). In your version, it returns NAN.

But as you say, we're now deep into the weeds...

-- Steve



More information about the Python-Dev mailing list