Python type() Function

Returns the type of an object

Usage

With one argument, the type() function returns the type of the specified object.

With three arguments, this function returns a new type object.

Syntax

type(object)

Python type() function parameters
ParameterConditionDescription
objectRequiredAny object (number, string, list, custom object etc.)

– OR –

type(name,bases,dict)

Python type() function parameters
ParameterConditionDescription
nameRequiredSpecifies the class name
basesOptionalSpecifies the base classes
dictOptionalSpecifies the namespace containing definitions for the class

type(object)

With one argument, the type() function returns the type of the specified object.

Example: Find type of below objects

x = type(42)
print(x)	# <class 'int'>
x = type('Hello')
print(x)	# <class 'str'>
x = type(['red', 'green', 'blue'])
print(x)	# <class 'list'>
x = type({'name': 'Bob', 'age': 25})
print(x)	# <class 'dict'>

Example: type() on custom object

class fruit:
  pass

apple = fruit()
print(type(apple))	# <class '__main__.fruit'>

You get ‘__main__.’ before the class name because it is local to the current module.

type(name, bases, dict)

With three arguments, this function returns a new type object.

For example, the following two statements create identical type objects.

Example: Create type object

class X:
	a = 1
X = type('X', (object,), dict(a=1))

type() vs isinstance()

The isinstance() method takes subclasses into account; type() doesn’t.

Example:

class fruit:
    pass

class apple(fruit):
    pass

print(isinstance(fruit(), fruit))	# True

print(type(fruit()) == fruit)		# True

print(isinstance(apple(), fruit))	# True

print(type(apple()) == fruit)		# False, and this probably won't be what you want.