Yandex

Python type() Function – Get the Type of an Object



Python type() Function

The type() function in Python is used to check the type of an object. It can also be used to create new types dynamically, though the most common use is checking the type of a variable.

Syntax

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

Parameters:

  • object – The object whose type you want to check.
  • name – (Advanced) Name of the new class to create.
  • bases – (Advanced) Tuple of parent classes.
  • dict – (Advanced) Dictionary of attributes and methods for the new class.

Returns:

  • For one argument: returns the type of the object.
  • For three arguments: returns a new type (class).

Example: Get Type of a Variable

x = 10
print(type(x))
<class 'int'>

Example: Type of Different Data Types

print(type(3.14))        # float
print(type("hello"))     # str
print(type([1, 2, 3]))    # list
print(type({ "a": 1 }))   # dict
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>

Use Case: Type Checking in Conditional Statements

value = "123"
if type(value) == str:
    print("It's a string!")
It's a string!

Advanced Use: Creating a Class Using type()

MyClass = type('MyClass', (), {'x': 5})
obj = MyClass()
print(obj.x)
5

In this form, type() is a metaclass constructor. It dynamically creates a class with name MyClass and an attribute x = 5.

Common Mistakes

  • Don't compare with 'int' or 'str' as strings. Use int, str, etc., directly.
  • Use isinstance() for safer type checking, especially with inheritance.

Interview Tip

type() is often used to check inputs in functions or debug issues. Knowing how it works helps in understanding Python's dynamic typing.

Summary

  • type(object) returns the class type of the object.
  • type(name, bases, dict) dynamically creates a new class.
  • Prefer isinstance() over type() when checking types in practice.

Practice Problem

Write a Python program that asks the user for input and prints the type of the entered value after converting it to int, float, or str.

value = input("Enter something: ")
try:
    print(type(int(value)))
except:
    try:
        print(type(float(value)))
    except:
        print(type(value))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M