The type() method returns the class type of the argument(object) passed as a parameter in Python. Python type() is a built-in function that is to return the type of data stored in the objects or variables in the program. For example, if a variable contains a value of 45.5 then the type of that variable is float.
Table of Content
- Parameters
- Syntax of the Python type() function
- Applications
- Extracting Details from Python Classes
- Python type() Function [With Easy Examples]
- Real-Life Usage of the type() function
- Conclusion
Parameters
- object: Required. If only one parameter is specified, the type() function returns the type of this object
- base: a tuple of classes from which the current class derives. Later corresponds to the _bases_ attribute
- dict: a dictionary that holds the namespaces for the class. Later corresponds to the _dict_ attribute
Syntax of the Python type() function
Syntax: type(object, bases, dict)
Python type() Example
a = ("Geeks", "for", "Geeks")
b = ["Geeks", "for", "Geeks"]
c = {"Geeks": 1, "for":2, "Geeks":3}
d = "Hello World"
e = 10.23
f = 11.22
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
Output
<class 'tuple'>
<class 'list'>
<class 'dict'>
<class 'str'>
<class 'float'>
<class 'float'>
Applications
type() function is basically useful for debugging purposes. When using other string functions like .upper(), .lower(), and .split() with text extracted from a web crawler, it might not work because they might be of different type which doesn’t support string functions. And as a result, it will keep throwing errors, which are very difficult to debug [Consider the error as GeneratorType has no attribute lower() ].
The type() function can be helpful at that point to determine the type of text extracted and then change it to other forms of string before we use string functions or any other operations on it.
type() with three arguments can be helpful to dynamically initialize classes or existing classes with attributes. It is also used to register database tables with SQL.
Check object parameter
print(type([]) is list)
print(type([]) is not list)
print(type(()) is tuple)
print(type({}) is dict)
print(type({}) is not list)
Output
True
False
True
True
True
Extracting Details from Python Classes
class Data:
"""Data Class"""
d_id = 10
class SubData(Data):
"""SubData Class"""
sd_id = 20
Let’s print some of the properties of these classes.
print(Data._class_)
print(Data._bases_)
print(Data._dict_)
print(Data._doc_)
print(SubData._class_)
print(SubData._bases_)
print(SubData._dict_)
print(SubData._doc_)
Output
<class 'type'>
(<class 'object'>,)
{'_module': 'main', 'doc': 'Data Class', 'd_id': 10, 'dict': <attribute 'dict' of 'Data' objects>, 'weakref': <attribute 'weakref_' of 'Data' objects>}
Data Class
<class 'type'>
(<class '_main_.Data'>,)
{'_module': 'main', 'doc_': 'SubData Class', 'sd_id': 20}
SubData Class
Python type() Function [With Easy Examples]
We use the type() function in Python to identify the type of a specific Python object. It’s a very straightforward function and an easy-to-understand one for that. Without any further ado, let’s get right into the syntax.
Syntax of the Python type() function
Python has a lot of built-in functions. The type() function is used to get the type of an object.
Python type() function syntax is
type(object)
type(name, bases, dict)
When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object._class_ instance variable.
When three arguments are passed, it returns a new type of object. It’s used to create a class dynamically on the fly.
- “name” string becomes the class name. It’s the same as the _name_ attribute of a class
- “bases” tuple specifies the base classes. It’s the same as the _bases_ attribute of the class
- “dict” dictionary helps create the class body. It’s the same as the _dict_ attribute of the class
Examples of the type() function in Python
Let’s look into some examples of using the type() function.
1. Finding the type of a Python object
x = 10
print(type(x))
s = 'abc'
print(type(s))
od = OrderedDict()
print(type(od))
class Data:
pass
d = Data()
print(type(d))
Output
<class 'int'>
<class 'str'>
<class 'collections.OrderedDict'>
<class '_main_.Data'>
Notice that the type() function returns the type of the object with the module name. Since our Python script doesn’t have a module, its module becomes _main_.
2. Extracting Details from Python Classes
Let’s say we have the following classes. We’ll pull metadata about the classes using the class, bases, dict, and doc properties.
class Data:
"""Data Class"""
d_id = 10
class SubData(Data):
"""SubData Class"""
sd_id = 20
print(Data._class_)
print(Data._bases_)
print(Data._dict_)
print(Data._doc_)
print(SubData._class_)
print(SubData._bases_)
print(SubData._dict_)
print(SubData._doc_)
Output
<class 'type'>
(<class 'object'>,)
{'_module': 'main', 'doc': 'Data Class', 'd_id': 10, 'dict': <attribute 'dict' of 'Data' objects>, 'weakref': <attribute 'weakref_' of 'Data' objects>}
Data Class
<class 'type'>
(<class '_main_.Data'>,)
{'_module': 'main', 'doc_': 'SubData Class', 'sd_id': 20}
SubData Class
We can create similar classes using the type() function.
Data1 = type('Data1', (object,), {'_doc_': 'Data1 Class', 'd_id': 10})
SubData1 = type('SubData1', (Data1,), {'_doc_': 'SubData1 Class', 'sd_id': 20})
print(Data1._class_)
print(Data1._bases_)
print(Data1._dict_)
print(Data1._doc_)
print(SubData1._class_)
print(SubData1._bases_)
print(SubData1._dict_)
print(SubData1._doc_)
Output
<class 'type'>
(<class 'object'>,)
{'_doc': 'Data1 Class', 'd_id': 10, 'module': 'main', 'dict': <attribute 'dict' of 'Data1' objects>, 'weakref': <attribute 'weakref_' of 'Data1' objects>}
Data1 Class
<class 'type'>
(<class '_main_.Data1'>,)
{'_doc': 'SubData1 Class', 'sd_id': 20, 'module': 'main_'}
SubData1 Class
Real-Life Usage of the type() function
Real-life usage of the “TYPE” function is useful when the behavior of another function depends on the type of value in a particular cell. If we are using functions that accept different types of data, TYPE can be used to find out what type of data is returned by a function or formula.
We want to create a function to calculate something on two integers. We can implement it in the following way.
def calculate(x, y, op='sum'):
if not(isinstance(x, int) and isinstance(y, int)):
print(f'Invalid Types of Arguments - x:{type(x)}, y:{type(y)}')
raise TypeError('Incompatible types of arguments, must be integers')
if op == 'difference':
return x - y
if op == 'multiply':
return x * y
# default is sum
return x + y
The type() function is used to print the type of the parameters when validation fails.
Conclusion
Actually, we have seen python types and functions, in this topic, we create basic and advanced syntax and examples of basic coding and program and this are not enough for us we need to work out more programs like this. I hope you under the basics of the python type() function. Share this with your friends and follow Publish Square for more Python tutorials like this