[Python-Dev] an alternative to embedding policy in PEP 418

Steven D'Aprano steve at pearwood.info
Thu Apr 5 00:50:54 CEST 2012


Oleg Broytman wrote:
> On Wed, Apr 04, 2012 at 11:03:02AM -0700, Ethan Furman wrote:
>> Oleg Broytman wrote:
>>>   . Pythonic equivalent of "get_clock(THIS) or get_clok(THAT)" is
>>>
>>> for flag in (THIS, THAT):
>>>    try:
>>>        clock = get_clock(flag)
>>>    except:
>>>        pass
>>>    else:
>>>        break
>>> else:
>>>    raise ValueError('Cannot get clock, tried THIS and THAT')
>>
>> Wow -- you'd rather write nine lines of code instead of three?
>>
>> clock = get_clock(THIS) or get_clock(THAT)
>> if clock is None:
>>     raise ValueError('Cannot get clock, tried THIS and THAT')
> 
>    Yes - to force people to write the last two lines. Without forcing
> most programmers will skip them.

You're not my real Dad! You can't tell me what to do!

*wink*

This level of paternalism is unnecessary. It's not your job to "force" 
programmers to do anything. If people skip the test for None, they will get an 
exception as soon as they try to use None as an exception, and then they will 
fix their broken code.

Although I don't like the get_clock() API, I don't think this argument against 
it is a good one. Exceptions are the *usual* error-handling mechanism in 
Python, but they are not the *only* mechanism, there are others, and it is 
perfectly okay to use non-exception based failures when appropriate. This is 
one such example.

"Return None on failure" is how re.match() and re.search() work, and it is a 
good design for when you have multiple fallbacks on failure.

result = re.match(spam, s) or re.match(ham, s) or re.match(eggs, s)
if result is None:
     raise ValueError('could not find spam, ham or eggs')


This is a *much* better design than nested tries:

try:
     result = re.match(spam, s)
except ValueError:
     try:
         result = re.match(ham, s)
     except ValueError:
         try:
             result = re.match(eggs, s)
         except ValueError:
             raise ValueError('could not find spam, ham or eggs')


Wow. Now *that* is ugly code. There's nothing elegant or Pythonic about being 
forced to write that out of a misplaced sense of purity.


-- 
Steven



More information about the Python-Dev mailing list