Python | type() function

type() method returns class type of the argument(object) passed as parameter. type() function is mostly used for debugging purposes.

Two different types of arguments can be passed to type() function, single and three argument. If single argument type(obj) is passed, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object.

Syntax :

type(object)
type(name, bases, dict)

Parameters :

name : name of 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.



Returntype :

returns a new type class or essentially a metaclass.

 

Code #1 :

# Python3 simple code to explain
# the type() function
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

 

Code #2 :

# Python3 code to explain
# the type() function
  
# Class of type dict
class DictType:
    DictNumber = {1:'John', 2:'Wick',
                  3:'Barry', 4:'Allen'}
      
    # Will print the object type
    # of existing class
    print(type(DictNumber))
  
# Class of type list    
class ListType:
    ListNumber = [1, 2, 3, 4, 5]
      
    # Will print the object type
    # of existing class
    print(type(ListNumber))
  
# Class of type tuple    
class TupleType:
    TupleNumber = ('Geeks', 'for', 'geeks')
      
    # Will print the object type
    # of existing class
    print(type(TupleNumber))
  
# Creating object of each class    
d = DictType()
l = ListType()
t = TupleType()

Output :

<class 'dict'>
<class 'list'>
<class 'tuple'>

 

Code #3 :

# Python3 code to explain
# the type() function
  
# Class of type dict
class DictType:
    DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'}
      
# Class of type list    
class ListType:
    ListNumber = [1, 2, 3, 4, 5]
  
# Creating object of each class   
d = DictType()
l = ListType()
  
# Will print accordingly whether both
# the objects are of same type or not  
if type(d) is not type(l):
    print("Both class have different object type.")
else:
    print("Same Object type")

Output :

Both class have different object type.

 
Code #4 : Use of type(name, bases, dict)

# Python3 program to demonstrate
# type(name, bases, dict)
  
# New class(has no base) class with the
# dynamic class initialization of type()
new = type('New', (object, ),
      dict(var1 ='GeeksforGeeks', b = 2009))
  
# Print type() which returns class 'type'
print(type(new))
print(vars(new))
  
  
# Base class, incorporated
# in our new class
class test:
    a = "Geeksforgeeks"
    b = 2009
  
# Dynamically initialize Newer class
# It will derive from the base class test
newer = type('Newer', (test, ),
        dict(a ='Geeks', b = 2018))
          
print(type(newer))
print(vars(newer))

Output :

{'__module__': '__main__', 'var1': 'GeeksforGeeks', '__weakref__': , 'b': 2009, '__dict__': , '__doc__': None}

{'b': 2018, '__doc__': None, '__module__': '__main__', 'a': 'Geeks'}

 
Applications :

  • type() function is basically used for debugging purposes. When used other string functions like .upper(), .lower(), .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() ] . type() function can be used 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 used to dynamically initialize classes or existing classes with attributes. It is also used to register database tables with SQL.


  • My Personal Notes arrow_drop_up

    Its lonely at the top

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.






User Actions