Python type() function is used to know the type of argument(object) passed as a parameter. It’s a built-in function, no need to import a special module. It’s a have 2 types of the variant.
Syntax
The type() function has two different forms:
type(object)
object: The type() returns the type of this object if one parameter is specified.
type(name, bases, dict)
Parameters
name: Name of the class, which later corresponds to the __name__ attribute of the class.
bases: 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.
Return
The type() function returns the type of the specified object.
Example of Python type Function
1. type() With a Single Object Parameter
Code 1. Simply Return the type of these objects and print in console.
a = ('apple', 'banana', 'cherry') b = "Hello World" c = 33 print(type(a)) print(type(b)) print(type(c))
Output:
Code 2: Check a data type
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
2. Use of type(name, bases, dict)
obj1 = type('X', (object,), dict(a='Foo', b=12)) print(type(obj1)) print(vars(obj1)) class test: a = 'Foo' b = 12 obj2 = type('Y', (test,), dict(a='Woo', b=99)) print(type(obj2)) print(vars(obj2))
Output:
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
<class 'type'>
{'a': 'Woo', 'b': 99, '__module__': '__main__', '__doc__': None}
Do comment if you have any doubts and suggestions on this tutorial.
Note: This example (Project) is developed in PyCharm 2019.3 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.