# How to get a Boolean from the type of an object?

I am trying to define the __init__ of a class, where I would like to support different types of input; in my case the input could be a either a list of pairs or a matrix. How do I write a Boolean function to test which kind of input I have? In the example code, I want to know how I should define the Boolean functions is_a_matrix(A) and is_a_tuple_of_pairs(A) (and of course more generally testing A to be of some other type)

class someclass():
def __init__(self, A):
if is_a_matrix(A):
self._matrix = A
if is_a_tuple_of_pairs(A):
self._matrix = somefunction(A)

edit retag close merge delete

Sort by » oldest newest most voted

For matrices, I don't know, this is a complex topic in Sage. For tuples of pairs, this is pure Python, and I suggest:

def is_a_pair(a):
return isinstance(a,tuple) and len(a)==2
def is_a_tuple_of_pairs(A):
if not isinstance(A,tuple):
return False
return all (is_a_pair(a) for a in A)


Note that if you accept lists in addition to tuples, you can use:

isinstance(a,(list,tuple))


inside these functions and so on.

more

Thanks Bétréma; it seems I can also use isinstance(A, type(matrix())) to check if something is a matrix (though I am not sure if this is the best way).

( 2013-03-26 02:15:32 +0200 )edit

## Stats

Seen: 400 times

Last updated: Mar 22 '13