Showing posts with label conditional. Show all posts
Showing posts with label conditional. Show all posts

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