Suppose,
var = ('x', 3)
How to check if a variable is a tuple with only two elements, first being a type str and the other a type int in python? Can we do this using only one check? I want to avoid this -
if isinstance(var, tuple):
if isinstance (var[0], str) and (var[1], int):
return True
return False
Here's a simple one-liner:
isinstance(v, tuple) and list(map(type, v)) == [str, int]
Try it out:
>>> def check(v):
return isinstance(v, tuple) and list(map(type, v)) == [str, int]
...
>>> check(0)
False
>>> check(('x', 3, 4))
False
>>> check((3, 4))
False
>>> check(['x', 3])
False
>>> check(('x', 3))
True
Well considering tuples are variable in length you're not going to find a method that checks this instance of all it's types. What's wrong with the method you have? It's clear what it does and it fits your usage. You're not going to find a pretty one liner AFAIK.
And you do have a one liner... Technically:
def isMyTuple(my_tuple):
return isinstance(my_tuple,(tuple, list)) and isinstance(my_tuple[0],str) and isinstance(my_tuple[1],int)
var = ('x', 3)
print isMyTuple(var)
If you're going to do this check many times, calling the method is DRY!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With