- How to check type of variable (object) in Python
- Python data are objects
- Different inbuilt object types in python
- Check type of variable in Python
- type() function
- class type (object)
- class type(name, bases, dict)
- isinstance() function
- type() vs isinstance()
- Conclusion
- References
- Leave a Comment Cancel reply
- Python Tutorial
- How to Check Type of Variable in Python
- 1. Checking Variable Type With Type() built-in function
- what is type()
- syntax
- Example 2: checking if the type of variable is a string
- 2. Checking Variable Type With isinstance() built-in function
- what is isinstance()
- sytnax
- example 1: checking variables type
- 4. Data Types in Python
- Related Tutorials:
- Python Print Type of Variable – How to Get Var Type
- How to Print the Type of a Variable in Python
- Final Thoughts
How to check type of variable (object) in Python
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 uniqueid 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 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 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')
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')
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')
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))
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__)
(,) NewClass Documentation', 'var': 'string', '__dict__': , '__weakref__': > 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,), ) print (NewClass1.__class__) print(NewClass1.__bases__) print(NewClass1.__dict__)
(,) NewClass1 Documentation', 'var': 'string', '__module__': '__main__', '__dict__': , '__weakref__': > 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.
isinstance(object, classinfo)
- 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:
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")
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
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
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
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 Cancel reply
Python Tutorial
- Python Multiline Comments
- Python Line Continuation
- Python Data Types
- Python Numbers
- Python List
- Python Tuple
- Python Set
- Python Dictionary
- Python Nested Dictionary
- Python List Comprehension
- Python List vs Set vs Tuple vs Dictionary
- Python if else
- Python for loop
- Python while loop
- Python try except
- Python try catch
- Python switch case
- Python Ternary Operator
- Python pass statement
- Python break statement
- Python continue statement
- Python pass Vs break Vs continue statement
- Python function
- Python call function
- Python argparse
- Python *args and **kwargs
- Python lambda function
- Python Anonymous Function
- Python optional arguments
- Python return multiple values
- Python print variable
- Python global variable
- Python copy
- Python counter
- Python datetime
- Python logging
- Python requests
- Python struct
- Python subprocess
- Python pwd
- Python UUID
- Python read CSV
- Python write to file
- Python delete file
- Python any() function
- Python casefold() function
- Python ceil() function
- Python enumerate() function
- Python filter() function
- Python floor() function
- Python len() function
- Python input() function
- Python map() function
- Python pop() function
- Python pow() function
- Python range() function
- Python reversed() function
- Python round() function
- Python sort() function
- Python strip() function
- Python super() function
- Python zip function
- Python class method
- Python os.path.join() method
- Python set.add() method
- Python set.intersection() method
- Python set.difference() method
- Python string.startswith() method
- Python static method
- Python writelines() method
- Python exit() method
- Python list.extend() method
- Python append() vs extend() in list
- Create your first Python Web App
- Flask Templates with Jinja2
- Flask with Gunicorn and Nginx
- Flask SQLAlchemy
How to Check Type of Variable in Python
In this tutorial, we’ll learn about getting and testing the type of variables by using two different ways, and finally, we’ll know the difference between these two ways.
1. Checking Variable Type With Type() built-in function
what is type()
type() is a python built function that returns the type of objects
syntax
As you can see, in the above code we have many different variables,
now let’s get the type of these variables.If you want to know all types of objects in python, you’ll find it in the final part of the article.
Example 2: checking if the type of variable is a string
let’s say that you want to test or check if a variable is a string, see the code bellow
As you can see, the code works very well, but this is not the best way to do that.
Remember!, if you want to check the type of variable, you should use isinstance() built function.2. Checking Variable Type With isinstance() built-in function
what is isinstance()
The isinstance() is a built-in function that check the type of object and return True or False
sytnax
example 1: checking variables type
#check if "list_var" is list print(isinstance(list_var, list)) #check if "string_var" is tuple print(isinstance(string_var, tuple)) #check if "tuple_var" is tuple print(isinstance(tuple_var, tuple)) #check if "dictionry_var" is dictionary print(isinstance(dictionry_var, dict))
if you want to get type of object use type() function.
if you want to check type of object use isinstance() function
4. Data Types in Python
Related Tutorials:
Python Print Type of Variable – How to Get Var Type
Kolade Chris
If you’re a Python beginner, becoming familiar with all its various data types can be confusing at first. After all, there are a lot of them available to you in the language.
In this article, I’m going to show you how to get the type of various data structures in Python by assigning them to a variable, and then printing the type to the console with the print() function.
How to Print the Type of a Variable in Python
To get the type of a variable in Python, you can use the built-in type() function.
The basic syntax looks like this:
In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
For instance, if the type is a string and you use the type() on it, you’d get as the result.
To show you the type() function in action, I’m going to declare some variables and assign to them the various data types in Python.
name = "freeCodeCamp" score = 99.99 lessons = ["RWD", "JavaScript", "Databases", "Python"] person = < "firstName": "John", "lastName": "Doe", "age": 28 >langs = ("Python", "JavaScript", "Golang") basics =
I will then print the types to the console by wrapping print() around some strings and the type() function.
print("The variable, name is of type:", type(name)) print("The variable, score is of type:", type(score)) print("The variable, lessons is of type:", type(lessons)) print("The variable, person is of type:", type(person)) print("The variable, langs is of type:", type(langs)) print("The variable, basics is of type:", type(basics))
Here are the outputs:
# Outputs: # The variable, name is of type: # The variable, score is of type: # The variable, lessons is of type: # The variable, person is of type: # The variable, langs is of type: # The variable, basics is of type:
Final Thoughts
The type() function is a valuable built-in function of Python with which you can get the data type of a variable.
If you’re a beginner, you should save yourself the hassle of cramming data types by using the type() function to print the type of a variable to the console. This will save you some time.
You can also use the type() function for debugging because in Python, variables are not declared with data types. So, the type() function was built into the language for you to check for data types of variables.