2017-06-17 3 views
0

私は変数tx_inを持っています。これはトランザクションが失敗した場合はdict、成功した場合はリストです。あとで処理されない例外が発生するのではなく、トランザクションが失敗した場合を除いてテストして正常に例外的に処理したい(別名tx_inはdictです)。リストまたは辞書のpython変数のテスト

変数が特定のタイプであるかどうかをテストするのではなく、ダックタイピングを使用する方が良いと思われるので、代わりにtx_inにtry catchを実装しました。 tx_inを操作しようとしましたが、それがリストであればトランザクションは成功し、コードの実行は続行されます。そうでなければ、PythonはKeyErrorを送出します。私はKeyErrorを捕まえた後、カスタムメッセージでそれを発生させます。

私の実装は以下の通りです。私のソリューションは業界の慣行に従うものですか?

try: 
    if tx_in[0]: 
     while tx_in[-1]["timestamp"] >= timestamp: 
      search = api.Transaction.getTransactionsList(recipientId=address, returnKey="transactions", limit=50, offset=len(tx_in), orderBy="timestamp:desc") 
      tx_in.extend(search) 
      if len(search) < 50: 
       break 

     # get all outputs 
     tx_out = api.Transaction.getTransactionsList(senderId=address, returnKey="transactions", limit=50, orderBy="timestamp:desc") 
     while tx_out[-1]["timestamp"] >= timestamp: 
      search = api.Transaction.getTransactionsList(senderId=address, returnKey="transactions", limit=50, offset=len(tx_out), orderBy="timestamp:desc") 
      tx_out.extend(search) 
      if len(search) < 50: 
       break 
     return sorted([t for t in tx_in+tx_out if t["timestamp"] >= timestamp], key=lambda e:e["timestamp"], reverse=True) 
except KeyError: 
    raise KeyError('Invalid address or null transactions.') 

答えて

2

ご判断ご使用のインスタンス・タイプに組み込み関数isinstanceを使用して、異なるプロセスに行くことができ

In [106]: help(isinstance) 
Help on built-in function isinstance in module __builtin__: 

isinstance(...) 
isinstance(object, class-or-type-or-tuple) -> bool 

Return whether an object is an instance of a class or of a subclass thereof. 
With a type as second argument, return whether that is the object's type. 
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for 
isinstance(x, A) or isinstance(x, B) or ... (etc.). 
関連する問題