Tutorial

Python type() Function Explained

Guide to python type() function: syntax, examples, dynamic class creation, and when to use isinstance().

Drake Nguyen

Founder · System Architect

3 min read
Python type() Function Explained
Python type() Function Explained

The python type() function is a built-in utility that serves two main roles: it returns the exact class of an object and it can construct new classes at runtime. This article explains the syntax, common uses with built-in and user-defined types, how to perform dynamic class creation (type(name, bases, dict)), and when to prefer isinstance() over type() for type checking. Examples and practical tips for debugging and metaprogramming are included.

Syntax of the python type() function

The python type() function accepts either one or three arguments. In the single-argument form it yields the runtime class of the object; in the three-argument form it creates a new type (a new class) dynamically.

# Single argument: get the class of an object
type(object)

# Three arguments: create a new class dynamically
# type(name, bases, dict)

Parameters for the three-argument form:

  • name — string used as the class __name__.
  • bases — tuple of base classes (the __bases__ attribute).
  • dict — mapping of attributes and methods for the class body (__dict__).

Examples of the python type() function

Finding the type of a Python object

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

s = 'abc'
print(type(s))  # <class 'str'>

from collections import OrderedDict
od = OrderedDict()
print(type(od))  # <class 'collections.OrderedDict'>

class Data:
    pass

d = Data()
print(type(d))  # <class '__main__.Data'>

Note: type(my_obj) returns the object's actual class (equivalent to my_obj.__class__). In scripts the module part of the class name may appear as __main__.

Inspecting class metadata

class Data:
    """Data Class"""
    d_id = 10

class SubData(Data):
    """SubData Class"""
    sd_id = 20

print(Data.__class__)
print(Data.__bases__)
print(Data.__dict__)
print(Data.__doc__)

print(SubData.__bases__)
print(SubData.__dict__)
print(SubData.__doc__)

These attributes are useful for introspection: __class__ shows the metaclass (usually type), __bases__ lists parent classes, __dict__ exposes attributes and methods, and __doc__ holds the class docstring.

Dynamic class creation with type()

# Create classes at runtime using type(name, bases, dict)
Data1 = type('Data1', (object,), {'__doc__': 'Data1 Class', 'd_id': 10})
SubData1 = type('SubData1', (Data1,), {'__doc__': 'SubData1 Class', 'sd_id': 20})

print(Data1.__name__)      # 'Data1'
print(issubclass(SubData1, Data1))  # True

# Adding a method dynamically
def greet(self):
    return f"hello from {self.__class__.__name__}"

Greeter = type('Greeter', (object,), {'greet': greet})
print(Greeter().greet())  # 'hello from Greeter'

The three-argument form is a core tool for python metaprogramming, ORMs, and frameworks that need runtime class generation or modification.

When to use type() vs isinstance()

Understanding the difference between type() and isinstance() is important for robust type checking and polymorphism.

  • type(obj) == SomeClass checks for an exact match: obj must be exactly an instance of SomeClass.
  • isinstance(obj, SomeClass) returns True when obj is an instance of SomeClass or any subclass — it respects inheritance and is the preferred approach in most conditional logic.
class Animal: pass
class Dog(Animal): pass

my_dog = Dog()
print(type(my_dog) == Animal)      # False
print(isinstance(my_dog, Animal))  # True

Best practices:

  • Use isinstance() for input validation and when inheritance should be accepted.
  • Use type() when you need the exact class, for example in serialization code that depends on precise types or when distinguishing unrelated classes.
  • Use type() in debugging or logging to display the exact object class (python get type of variable for diagnostics).

Real-world uses and tips

  • Debugging and logging: print(type(obj)) to quickly inspect the python object class during development or troubleshooting.
  • Metaprogramming: type(name, bases, dict) enables python dynamic class creation used by ORMs, serializers, and plugin systems.
  • Runtime adapters: generate lightweight adapter classes on the fly when integrating with external systems.
# Example: logging a value's exact class
def log_value(v):
    print(f"Value: {v!r}, type: {type(v)}")

log_value([1,2,3])  # shows the exact class for debugging

FAQs

What does the python type() function Netalith?

It returns an object's class when called with one argument, and when called with three arguments (type(name, bases, dict)) it creates a new class at runtime. This dual behavior makes type() both a simple introspection tool and a building block for python metaprogramming.

How Netalith I check the type of a variable in Python?

Use type(variable) to get the exact class. For conditional checks prefer isinstance(variable, Type) to accept subclasses. Example: isinstance(x, int) vs type(x) == int.

When should I use type(name, bases, dict)?

Use the three-argument form when you need to define classes programmatically — common in frameworks, dynamic model generation, or when implementing custom metaclasses.

How is type() related to metaclasses?

type is the default metaclass in Python. When you create a class using class syntax, Python actually calls type behind the scenes (type(name, bases, dict)). Advanced metaprogramming may subclass type to customize class creation.

Can type() show module information?

Yes. When you print a class returned by type(), you might see the module qualified name like <class '__main__.MyClass'> or the real module path for imported modules.

Conclusion

The python type() function is a versatile tool: use its single-argument form for precise type inspection and logging, and the three-argument form for dynamic class creation and metaprogramming. For everyday type checks in application logic prefer isinstance() to handle inheritance and polymorphism gracefully. Together, these tools help you write clearer, more flexible Python code.

References

Official documentation: https://docs.python.org/3/library/functions.html#type

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.