Type method python

Understanding the type() Function in Python

The type() function in Python is used to determine the class type of an object. It returns the type of the object passed to it as a parameter.


Syntax of type()

type(object)
# OR
type(object, bases, dict)

Parameters:

  • object: (Required) If only one argument is passed, type() returns the type of this object.

  • bases: (Optional) A tuple of base classes. Used when creating a new type.

  • dict: (Optional) A dictionary that defines the namespace of the class.

Return Value:

  • With one argument: returns the type of the object.

  • With three arguments: returns a new type/class (essentially, a metaclass).


Example 1: Using type() with a Single Object

In this example, we use type() to check the type of various objects:

a = ("blog", "for", "blog") b = ["blog", "for", "blog"] c = {"blog": 1, "for": 2, "blog": 3} d = "Hello World" e = 10.23 f = 11.22 print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) print(type(f))

Output:

<class 'tuple'> <class 'list'> <class 'dict'> <class 'str'> <class 'float'> <class 'float'>

What Does type() Do?

The type() function is commonly used for debugging and dynamic class creation.

Use with One Argument:

type(object)

đŸ‘€Returns the type of the given object.

Use with Three Arguments:

type(object_name, bases, dict)
  • Creates a new type (class).

  • Useful for dynamic class creation and metaprogramming.


Practical Applications

  • Debugging:
    When processing data from different sources (e.g., web scraping), you may encounter objects that do not behave like standard strings. The type() function can help identify the object type to avoid errors like:
    'GeneratorType has no attribute lower()'

  • Dynamic Class Creation:
    The three-argument form of type() is used to create classes dynamically or register database tables (common in ORMs like SQLAlchemy).

  • Type Checking:
    You can use type() to validate object types during runtime.


Example 2: Using type() for Boolean Checks

You can compare object types using is and is not:

print(type([]) is list) print(type([]) is not list) print(type(()) is tuple) print(type({}) is dict) print(type({}) is not list)

Output:

True False True True True

Summary

  • The type() function is a built-in Python function that returns the type of an object.

  • It is very useful for debugging, validating object types, and dynamic class creation.

  • You can pass one argument (to get an object’s type) or three arguments (to create a new class).

Popular Posts