0
0
PythonHow-ToBeginner · 3 min read

How to Use type() Function in Python: Syntax and Examples

In Python, the type() function returns the type of an object or can create a new type dynamically. Use type(object) to find the type, or type(name, bases, dict) to create a new class.
📐

Syntax

The type() function has two main uses:

  • Check type: type(object) returns the type of the given object.
  • Create type: type(name, bases, dict) creates a new class dynamically, where:
    • name is the class name (string).
    • bases is a tuple of base classes.
    • dict is a dictionary of attributes and methods.
python
type(object)
type(name, bases, dict)
💻

Example

This example shows how to use type() to check the type of variables and create a new class dynamically.

python
x = 10
print(type(x))  # Shows the type of x

class MyClass:
    pass

obj = MyClass()
print(type(obj))  # Shows the type of obj

# Create a new class dynamically
NewClass = type('NewClass', (object,), {'greet': lambda self: 'Hello!'})
instance = NewClass()
print(type(instance))  # Type of the new instance
print(instance.greet())  # Call method from dynamic class
Output
<class 'int'> <class '__main__.MyClass'> <class '__main__.NewClass'> Hello!
⚠️

Common Pitfalls

Common mistakes when using type() include:

  • Confusing type(object) (to check type) with type(name, bases, dict) (to create classes).
  • Forgetting that the dynamic class creation requires a tuple for base classes, even if empty (()).
  • Using mutable default arguments in the dict can cause unexpected behavior.
python
wrong = type('WrongClass', object, {})  # Incorrect bases argument, should be a tuple
correct = type('CorrectClass', (object,), {})  # Correct usage
print(type(wrong))  # This will raise a TypeError
print(type(correct))  # This works fine
Output
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: type() arg 2 must be tuple, not type
📊

Quick Reference

Use this quick guide to remember type() usage:

  • Check type: type(obj) returns the object's type.
  • Create class: type(name, (bases,), dict) creates a new class.
  • Base classes: Always use a tuple, even if empty.
  • Attributes: Provide methods and variables in the dictionary.

Key Takeaways

Use type(object) to find the type of any Python object.
Use type(name, bases, dict) to create new classes dynamically.
Always pass base classes as a tuple when creating classes with type().
Remember that type() with one argument checks type; with three arguments creates a class.
Avoid common mistakes like passing a single class instead of a tuple for bases.