Python type

Python type() builtin function is used get the type of specified object.

In this tutorial, we will learn about the syntax of Python type() function, and learn how to use this function with the help of examples.

Syntax

There are two forms for type() function based on the number of parameters it can take.

The syntax of type() function with object is

type(object)

where

Parameter Required/Optional Description
object Required A Python object.

The syntax of type() function with name of object, base classes, and dictionary is

type(name, bases, dict, **kwds)

where

Parameter Required/Optional Description
name Required A string. String representing the name of object.
bases Required A tuple. This represents the base classes for the object.
dict Required A dictionary. This contains attribute and method definitions offer the class body.
**kwds Optional Keyword parameters.

Returns

The function returns a type object.

Examples

1 Type of Object

In this example, we take a Python object x, and find its type programmatically using type() function.

Python Program

x = [1, 2, 4, 8]
print(type(x))

Output

<class 'list'>

2 Type of Object specified via String

In this example, we define a class A with two attributes. We find the type of the object specified by string 'A' whose attribute is name='Apple'.

Python Program

class A:
    name = 'Apple'
    num = 25

print(type('A', (), dict(name='Apple')))

Output

<class '__main__.A'>

Conclusion

In this Python Tutorial, we have learnt the syntax of Python type() builtin function, and also learned how to use this function, with the help of Python example programs.