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.

# Find type of below objects

x = type(42)
print(x)
# Prints <class 'int'>

x = type('Hello')
print(x)
# Prints <class 'str'>

x = type(['red', 'green', 'blue'])
print(x)
# Prints <class 'list'>

x = type({'name': 'Bob', 'age': 25})
print(x)
# Prints <class 'dict'>

Let’s try type() on a custom object.

class fruit:
  pass

apple = fruit()
print(type(apple))
# Prints <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.

# The usual way
class X:
	a = 1

# With type function
X = type('X', (object,), dict(a=1))

type() vs isinstance()

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

class fruit:
    pass

class apple(fruit):
    pass

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

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

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

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