Ask Your Question
0

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

asked 2013-03-22 07:02:18 +0100

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 flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2013-03-22 08:44:08 +0100

updated 2013-03-22 08:54:54 +0100

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.

edit flag offensive delete link more

Comments

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).

Amri gravatar imageAmri ( 2013-03-26 02:15:32 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-03-22 07:02:18 +0100

Seen: 440 times

Last updated: Mar 22 '13