How to check type of variable (object) in Python


Written By - admin
Advertisement

Python is not a typed language. What that means is that objects are identified by what they can do rather than what they are. In this tutorial we will learn how to check and print type of variable in Python

 

Python data are objects

  • Python follows and what we call as Object Model, now what does that mean?
  • Every number, string, data structure, function, class, module, and so on exists in the Python interpreter in its own "box," which is referred to as a Python object.
  • Each object has an identity, a type, and a value.
  • For example, when you write a = 42, an integer object is created with the value of 42.
  • In Python, an object is a chunk of data that contains at least the following:
    • A type that defines what it can do
    • A unique id to distinguish it from other objects
    • A value consistent with its type
    • A reference count that tracks how often this object is used

 

Different inbuilt object types in python

  • This table shows that inbuilt supported object types for Python.
  • The second column (Type) contains the Python name of that type.
  • The third column (Mutable?) indicates whether the value can be changed after creation
  • Examples shows one or more literal examples of that type.
Name Type Mutable? Examples
Boolean bool no True, False
Integer int no 53, 5000, 5_400
Floating Point float no 2.56, 3.1e5
Complex complex no 3j, 5 + 9j
Text String str no 'abcd', "def", '''ghi'''
List list yes ['abc', 'def', 'ghi']
Tuple tuple no ('abc', 'def', 1997, 2000)
(1, 2, 3, 4, 5 )
Bytes bytes no b'ab\xff'
ByteArray bytearray no bytearray(...)
Set set yes set([3, 5, 7])
FrozenSet frozenset no frozenset(['Elsa', 'Otto'])
Dictionary dict yes {'game': 'bingo', 'dog': 'dingo', 'drummer': 'Ringo'}

 

Check type of variable in Python

In Python you can use type() and isinstance() to check and print the type of a variable. We will cover both these functions in detail with examples:

 

type() function

  • An object’s type is accessed by the built-in function type(). There are no special operations on types.
  • The standard module types defines names for all standard built-in types.
  • Types are written like this: <class 'int'>

class type (object)

  • Returns the type of object.
  • The type is returned as a type object as defined as a built-in object or in the types module.
  • The type of an object is itself an object.
  • This type object is uniquely defined and is always the same for all instances of a given type.
  • Therefore, the type can be compared using the is operator.
  • All type objects are assigned names that can be used to perform type checking.

In this python script type(var) is checking if the value of var is of type integer

#!/usr/bin/env python3

var = 10

# Check if 10 (which is the value of var) is integer
if type(var) is int:
    print('Is an integer')

Output:

Is an integer

Similarly to check if variable is list type

#!/usr/bin/env python3

# Assigned a list to var object
var = ['10','abcd','1234']

# Check if the value of var contains list type
if type(var) is list:
    print('Is a list')

Output:

Is a list

Or another method to check type of variable using type()

#!/usr/bin/env python3

# Assigned a list to var object
var = ['10','abcd','1234']

# Check if the value of var contains list type
if type(var) == list:
    print('Is a list')

Output:

Advertisement
Is a list

To print the variable type we can just call print with type() function

#!/usr/bin/env python3

# Assigned a list to var object
var = ['10','abcd','1234']

# Print the type of variable
print(type(var))

Output:

<class 'list'>

 

class type(name, bases, dict)

  • Creates a new type object (which is the same as defining a new class).
  • name is the name of the type and becomes the __name__ attribute
  • bases is a tuple of base classes and becomes the __bases__ attribute
  • dict is a dictionary containing definitions corresponding to a class body and becomes the __dict__ attribute
  • The use case for type(name, bases, dict) is when you want to dynamically generate classes at runtime.

In this example we create a class and print individual properties:

#!/usr/bin/env python3

class NewClass:
    """NewClass Documentation"""
    var = 'string'

print (NewClass.__class__)
print(NewClass.__bases__)
print(NewClass.__dict__)
print(NewClass.__doc__)

Output:

<class 'type'>
(<class 'object'>,)
{'__module__': '__main__', '__doc__': 'NewClass Documentation', 'var': 'string', '__dict__': <attribute '__dict__' of 'NewClass' objects>, '__weakref__': <attribute '__weakref__' of 'NewClass' objects>}
NewClass Documentation

Now we can achieve the same and define a class using type(name, bases, dict) function

#!/usr/bin/env python3

NewClass1 = type('NewClass1', (object,), {'__doc__': 'NewClass1 Documentation', 'var': 'string'})

print (NewClass1.__class__)
print(NewClass1.__bases__)
print(NewClass1.__dict__)

Output:

<class 'type'>
(<class 'object'>,)
{'__doc__': 'NewClass1 Documentation', 'var': 'string', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'NewClass1' objects>, '__weakref__': <attribute '__weakref__' of 'NewClass1' objects>}
NewClass1 Documentation

 

isinstance() function

  • The isinstance() function is used to validate the input argument type.
  • Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.
  • If object is not an object of the given type, the function always returns False.

Syntax:

isinstance(object, classinfo)

Here,

  • object which has to be checked
  • classinfo can be a class, type or also be a tuple of classes and/or types.
#!/usr/bin/env python3

# Define var object
var = 'some value'

# Check variable type and return boolean value
print(isinstance(var, str))

Output returns boolean value:

True

Similarly in if condition

#!/usr/bin/env python3

# Define var object
var = 'some value'

# Check variable type and return boolean value
if isinstance(var, str):
    print("Is a string")

Output:

Is a string

isinstance() can accept a tuple of types if you want to check that an object’s type is among those present in the tuple:

#!/usr/bin/env python3

# Define var object
var = 4.5

# Check variable type using tuple class and return boolean value
if isinstance(var, (int, float)):
    print("Is either an integer or float type")

Note the second parenthesis, surrounding two value types we pass in. This parenthesis represents a tuple, one of the data structures. Output:

Is either an integer or float type

 

type() vs isinstance()

Both type() and isinstance() function can be used to check and print the type of a variable but the isinstance() built-in function is recommended for testing the type of an object, because it also takes subclasses into account.

Moreover with isinstance() you can also get boolean return value as True or False which can be used as decision making

You can learn more on this topic at What are the differences between type() and isinstance()?

 

Advertisement

Conclusion

In this tutorial we learned to check and print the type of a variable in python. We have type() and isinstance() function where both can be used to check variable type where both have their own benefits so you can choose one depending upon your requirement

Lastly I hope this tutorial to learn more about type() and isinstance() function to print type of a variable using Python was helpful. So, let me know your suggestions and feedback using the comment section.

 

References

I have used below external references for this tutorial guide
type() function
Python - type(name,bases,dict)
isinstance()
Introducing Python

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment