changeset: 75781:9a7dcfbcf726 branch: 3.2 parent: 75778:613919591a05 user: Georg Brandl date: Sat Mar 17 16:58:05 2012 +0100 files: Doc/faq/design.rst description: Closes #14306: clarify expensiveness of try-except and update code snippet diff -r 613919591a05 -r 9a7dcfbcf726 Doc/faq/design.rst --- a/Doc/faq/design.rst Sat Mar 17 00:40:34 2012 -0700 +++ b/Doc/faq/design.rst Sat Mar 17 16:58:05 2012 +0100 @@ -284,8 +284,9 @@ How fast are exceptions? ------------------------ -A try/except block is extremely efficient. Actually catching an exception is -expensive. In versions of Python prior to 2.0 it was common to use this idiom:: +A try/except block is extremely efficient if no exceptions are raised. Actually +catching an exception is expensive. In versions of Python prior to 2.0 it was +common to use this idiom:: try: value = mydict[key] @@ -296,11 +297,10 @@ This only made sense when you expected the dict to have the key almost all the time. If that wasn't the case, you coded it like this:: - if mydict.has_key(key): + if key in mydict: value = mydict[key] else: - mydict[key] = getvalue(key) - value = mydict[key] + value = mydict[key] = getvalue(key) For this specific case, you could also use ``value = dict.setdefault(key, getvalue(key))``, but only if the ``getvalue()`` call is cheap enough because it

AltStyle によって変換されたページ (->オリジナル) /