Update PEP 463 with Chris Angelico's latest version, with slightly fixed

formatting.
This commit is contained in:
Thomas Wouters 2014-02-27 23:32:04 +01:00
parent a5e9dcb7fd
commit ed9a6f379b
1 changed files with 43 additions and 1 deletions

View File

@ -43,6 +43,34 @@ support this.
* statistics.mean(data) - no way to handle an empty iterator * statistics.mean(data) - no way to handle an empty iterator
Had this facility existed early in Python's history, there would have been
no need to create dict.get() and related methods; the one obvious way to
handle an absent key would be to respond to the exception. One method is
written which signals the absence in one way, and one consistent technique
is used to respond to the absence. Instead, we have dict.get(), and as of
Python 3.4, we also have min(... default=default), and myriad others. We
have a LBYL syntax for testing inside an expression, but there is currently
no EAFP notation; compare the following::
# LBYL:
if key in dic:
process(dic[key])
else:
process(None)
# As an expression:
process(dic[key] if key in dic else None)
# EAFP:
try:
process(dic[key])
except KeyError:
process(None)
# As an expression:
process(dic[key] except KeyError: None)
Python generally recommends the EAFP policy, but must then proliferate
utility functions like dic.get(key,None) to enable this.
Rationale Rationale
========= =========
@ -338,6 +366,20 @@ Translate numbers to names, falling back on the numbers::
except KeyError: except KeyError:
u = tarinfo.uid u = tarinfo.uid
Look up an attribute, falling back on a default::
mode = (f.mode except AttributeError: 'rb')
# Lib/aifc.py:882:
if hasattr(f, 'mode'):
mode = f.mode
else:
mode = 'rb'
return (sys._getframe(1) except AttributeError: None)
# Lib/inspect.py:1350:
return sys._getframe(1) if hasattr(sys, "_getframe") else None
Perform some lengthy calculations in EAFP mode, handling division by Perform some lengthy calculations in EAFP mode, handling division by
zero as a sort of sticky NaN:: zero as a sort of sticky NaN::
@ -616,7 +658,7 @@ An examination of use-cases shows that this is not needed as often as
it would be with the statement form, and as its syntax is a point on it would be with the statement form, and as its syntax is a point on
which consensus has not been reached, the entire feature is deferred. which consensus has not been reached, the entire feature is deferred.
Multiple 'except' keywords can be used, and they will all catch Multiple 'except' keywords could be used, and they will all catch
exceptions raised in the original expression (only):: exceptions raised in the original expression (only)::
# Will catch any of the listed exceptions thrown by expr; # Will catch any of the listed exceptions thrown by expr;