contextlib.suppress
を使用して、try
/except
の代わりにpass
の例外を抑制する理由を教えてください。パスでtry/exceptと反対にcontextlib.suppressを使う理由は?
suppress
は、複数の文字を持っている場合)、およびコードは、多くの場合、文字の代わりにLOCでカウントされていても、
suppress
も
try
よりもはるかに遅いように思わはありません
/どちらの場合もexcept
、エラーが発生し、それがないとき:
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from timeit import timeit
>>> # With an error
>>> timeit("""with suppress(ValueError):
x = int('a')""", setup="from contextlib import suppress")
1.9571568971892543
>>> timeit("""try:
x = int('a')
except ValueError:
pass""")
1.0758466499161656
>>> # With no error
>>> timeit("""with suppress(ValueError):
x = int(3)""", setup="from contextlib import suppress")
0.7513525708063895
>>> timeit("""try:
x = int(3)
except ValueError:
pass""")
0.10141028937128027
>>>
2行を保存します。 –
同様に、forループを使用できるときに 'any()'または 'all()'を使うのはなぜですか?私は 'contextlib.suppress'を使うと読みやすさとメンテナンスに役立つと思います。 –
@SimeonVisser 'any()'と 'all()' *は明らかにコードを短くします。 'any()'と 'all()'は 'for'ループよりもパフォーマンスが速いことも確信しています。私が見る限りでは、 'suppress'を使う唯一の理由は、それがもっと読みやすいということです。一方、 'try/except'を使うことは* much *速くなります。 –