過去に、次のような try-except 句を書いていることに非常に気付きました。これの主な理由は、より少ないコードを記述することです。
class Synchronizer(object):
# ...
def _assert_dir(self, dirname, argname, argnum):
""" *Private*. Raises OSError if the passed string does not point
to an existing directory on the file-system. """
if not os.path.isdir(dirname):
message = 'passed `%s` argument (%d) does not point to a ' \
'directory on the file-system.'
raise OSError(message % (argname, argnum))
def synchronize(self, source_dir, dest_dir, database):
# Ensure the passed directories do exist.
try:
self._assert_dir(source_dir, 'source_dir', 2)
self._assert_dir(dest_dir, 'dest_dir', 3)
except OSError:
raise
# ...
そうでなければ私は書く必要があったので、私はこのようにしていた
class Synchronizer(object):
# ...
def synchronize(self, source_dir, dest_dir, database):
# Ensure the passed directories do exist.
if not os.path.isdir(source_dir):
message = 'passed `source_dir` argument (2) does not point to a ' \
'directory on the file-system.'
raise OSError(message)
if not os.path.isdir(dest_dir):
message = 'passed `dest_dir` argument (3) does not point to a ' \
'directory on the file-system.'
raise OSError(message)
# ...
私は実際には、チェック アンド レイズ操作を行うメソッドを記述するというアイデアが好きですが、大きな欠点が 1 つあります。それは、読みやすさです。特にコードの折り畳みを行うエディターにとって、try
ステートメントは読者に内部で何が起こっているかをあまり伝えていませんが、if not os.path.isdir(source_dir)
かなり良いヒントです。
IMHO try-except 句が必要なのは、例外の発生元である例外のキャッチャー(トレースバックのリーダー) を混乱させるためです。
このデザインについてどう思いますか?それはあなたにとってひどいですか、素晴らしいですか、それとも混乱しますか? または、状況を改善する方法について何かアイデアはありますか?