- 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
- Check Variable Type in Python
- Variables and Their Types in Python
- Check the Type of a Variable in Python
- Use the type() Function to Check Variable Type in Python
- Use the isinstance() Function to Check Variable Type in Python
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
Check Variable Type in Python
- Variables and Their Types in Python
- Check the Type of a Variable in Python
- Use the type() Function to Check Variable Type in Python
- Use the isinstance() Function to Check Variable Type in Python
In Python, if you want to store any kind of data, perform some operations on that data or pass the data between functions or objects, you first have to store that data somewhere. It is done with the help of a variable.
Variables and Their Types in Python
A variable is nothing but a box or container inside which our data will be stored. The variable will be allocated to some space in memory (RAM). The data type tells us what type of data a variable holds. And depending on the type of data, the compiler will decide how much space to allocate to that variable inside the memory. And then will assign the memory accordingly.
In Python, you don’t have to explicitly define the type of data you will store inside the variable as you do in C/C++, Java, or any other major programming languages. Here, you can directly assign the value to the variable, and the compiler will identify what type of data the variable holds and in which class it belongs to the integer, string, list, etc.
# Variable of type String newVariable = "This is a new variable" print(newVariable) # Variable of type Boolean booleanVariable = True print(booleanVariable) # Variable of type Float floatVariable = 20.30 print(floatVariable)
This is a new variable True 20.3
Check the Type of a Variable in Python
- Number: This category contains integers, floating-point numbers, and complex numbers.
- String: It is a sequence of Unicode characters. A Unicode is a character set that contains characters and symbols from all languages around the world.
- Boolean: Boolean represents either True or False .
- List: It is an ordered collection of elements of the different data types. Lists are mutable, which means values inside the list can be changed after it has been created.
- Tuple: It is also an ordered collection of elements of the different data types. The only difference between a list and a tuple is that tuples are immutable, which means that once they are created, they cannot be modified.
- Set: A Set is an unordered collection of unique items.
- Dictionary: It is an unordered collection of key-value pairs. The key and value can be of any type.
There are two ways in which you can check the type of a variable in Python.
Use the type() Function to Check Variable Type in Python
To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.
myInt = 50 print(type(myInt)) myFloat = 10.50 print(type(myFloat)) myString = "My name is Adam" print(type(myString))
class 'int'> class 'float'> class 'str'>
Use the isinstance() Function to Check Variable Type in Python
Another function that can be used to check the type of a variable is called isinstance() . You need to pass two parameters; the first is the variable (the value whose data type you want to find), and the second parameter is the variable type. If the variable type is identical to the type you have specified in the second parameter, it will return True and False otherwise.
# A variable 'myVar' having a value 50 inside myVar = 50 # Printing the value returned by isinstance() function print("Does myVar belongs to int: ",isinstance(myVar, int)) # This will return false # As the value passed is string and you are checking it with int print("Does string belongs to int: ",isinstance("My String", int)) complexNo = 1 + 2j print("This this number complex: ",isinstance(complexNo, complex))