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
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,
Labels:
conditional,
data type,
Python2.7
Subscribe to:
Post Comments (Atom)
Nice Renaldo! seems interesting blog..keep it up!
ReplyDeleteThanks :)
DeleteThat 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.
ReplyDeleteWhy would you like to do that test in the first place?.
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