1

I have an exception from which I'm trying to get args, but if fails.

print hasattr(e, 'args')
print type(e.args)
print hasattr(e.args, '1')
print hasattr(e.args, '0')
print '1' in e.args
print '0' in e.args
print 1 in e.args
print 0 in e.args
print e.args[0]
print e.args[1]

This prints:

True
<type 'tuple'>
False
False
False
False
False
False
Devices not found
4
Kin
  • 4,466
  • 13
  • 54
  • 106
  • possible duplicate of [To check whether index of list exists](http://stackoverflow.com/questions/19565745/to-check-whether-index-of-list-exists) – vaultah Jul 02 '14 at 14:30
  • I'm not sure what you want. You want to check if `e.args[N]` exists or you want to check if a specific value is part of `e.args`? – netcoder Jul 02 '14 at 14:32
  • @netcoder fist, if `e.args[0]` exists – Kin Jul 02 '14 at 14:34
  • 3
    Just check then length of `e.args`. If `len(e.args) == 1` then `e.args[0]` exists, if `len(e.args) == 2`, then `e.args[1]` exists, and so on. You cannot have empty elements in tuples and they are zero-indexed. – netcoder Jul 02 '14 at 14:35

2 Answers2

1

You simply use the in operator:

>>> try:
...   raise Exception('spam', 'eggs')
... except Exception as inst:
...   print inst.args
...   print 'spam' in inst.args
... 
('spam', 'eggs')
True

If your code is returning False then most likely 1 wasn't an argument to the exception. Perhaps post the code where the exception was raised.

You can check if the tuple has positions 0 to N by doing len.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
0

You can check the length of your tuple:

t = 1, 2, 3,
if len(t) >= 1:
    value = t[0]    # no error there

...or you can just check for an IndexError, which I'd say is more pythonic:

t = 1, 2, 3,
try:
    value = t[4]
except IndexError:
    # handle error case
    pass

The latter is a concept named EAFP: Easier to ask for forgiveness than permission, which is a well known and common Python coding style.

Community
  • 1
  • 1
netcoder
  • 66,435
  • 19
  • 125
  • 142