0

Python: Getting to know the object type

If you are dealing with API’s or plugins(classes/methods)  written by other developers, we might encounter some issues dealing with mismatch type, like adding float object to a string object, adding string values to integer objects or any other cases which could throw an exception error on the runtime, type() function will help us to identify the object type.

Sample Scenario:

var1 = "1"
var2 = 1

var3 = var1 + var2

Result:

C:\python>python mismatch_2.py
Traceback (most recent call last):
  File "C:\python\mismatch_2.py", line 6, in <module>
    var3 = var1 + var2
TypeError: can only concatenate str (not "int") to str

Syntax:

type(value)

Example:

var1 = "1"
var2 = 1
var3 = 1.250
var4 = {1}
var5 = [1]
var6 = {1:1}

print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
print(type(var5))
print(type(var6))

Sample Result:

C:\python>python type_sample1.py
<class 'str'>
<class 'int'>
<class 'float'>
<class 'set'>
<class 'list'>
<class 'dict'>

If you are going to transform data into other type, you will need to do a “Type Conversion/Casting” which will be written in my upcoming blogs.

Kevin San Jose, VCP6-DCV

Kevin San Jose, VCP6-DCV

LFCS, MTCRE, VCP6-DCV

Leave a Reply

Your email address will not be published. Required fields are marked *