Thursday, March 31, 2016

Checking the type of a variable or object

Recently, I came across to the problem of writing a function that behaves differently according the type of its single input parameter.  Due the fact that Python is a dynamically-typed language, this problem does not look  too easy to me at first glance. But fortunately, Python provides the build- in command  isinstance. This command receives two parameters, the first one is a object and the second is a class or tuple of classes. Then return  true is the object is an instance of the class or of the classes in the tuple. Let us exemplify the use of this function with a routine that print the type of its input parameter,
def printType(x):
    if isinstance(x,(int,long,float,complex)):
        print "It's a number"
        return
    if isinstance(x, str):
        print "It's a string"
        return
    if isinstance(x,list):
        print "It's a list"
        return
    if isinstance(x,dict):
        print "It's a dictionary"
        return
    if isinstance(x,tuple):
        print "It's a tuple"
        return

4 comments:

  1. Nice Renaldo! seems interesting blog..keep it up!

    ReplyDelete
  2. That fix your problem, but it is likely you could rethink the solution again. Think about the concept "DuckTyping". It is rare to do this kind of checking in Python. We try to avoid it. A different design on your solution could do the job without that type testing. But it will imply a different design.

    Why would you like to do that test in the first place?.

    ReplyDelete
    Replies
    1. I wrote a function to plot the sparse pattern of different types of sparse matrices. Besides, we didn't want to call a transformation to Scipy format before every call of that function.

      Delete