Reputation: 427
I have a variable tx_in
which is a dict if the transaction has failed and a list if it has succeeded. Rather than hit an unhandled exception later on, I want to test and gracefully except if transaction failed (aka tx_in
is a dict).
Considering it seems better practice to use Duck Typing instead of trying to test if a variable is a particular type, I have instead implemented a try catch on tx_in
. I try to manipulate the tx_in
and if it's a list, transaction is successful and code execution continues. If it is not, python will raise KeyError. I catch KeyError and then raise it with a custom message.
My implementation is below. Is my solution acceptable industry practice?
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.')
Upvotes: 0
Views: 76
Reputation: 308
you can use the built-in function isinstance
to judgment your instance type, and go on different process
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.).
Upvotes: 2