Kin
Kin

Reputation: 4596

How to check if tuple has element?

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

Upvotes: 1

Views: 3623

Answers (2)

Martin Konecny
Martin Konecny

Reputation: 59591

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.

Upvotes: 1

netcoder
netcoder

Reputation: 67695

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.

Upvotes: 0

Related Questions