How To Get Type Of Variable In Python

In Python, variables can store different types of data, such as integers, strings, lists, and more. When writing
code, it’s not uncommon to need to know the type of a specific variable. This can help you debug your code, ensure
that you’re using the correct type of data, or even help you write more flexible code that can handle various
data types. In this blog post, we’ll explore how to get the type of a variable in Python!

Using the type() Function

The simplest and most straightforward way to get the type of a variable in Python is to use the built-in
type() function. This function takes one argument – the variable whose type you want to determine –
and returns the type of the given variable. Let’s take a look at a few examples:

        # Example 1: Get the type of an integer
        number = 42
        print(type(number))  # Output: <class>

        # Example 2: Get the type of a string
        text = "Hello, Python!"
        print(type(text))  # Output: <class>

        # Example 3: Get the type of a list
        my_list = [1, 2, 3, 4, 5]
        print(type(my_list))  # Output: <class>
        

As you can see, the type() function returns the type of the variable in the format <class
‘type_name’>
. In most cases, you’ll be interested in the actual type name, such as int,
str, or list. To get this information, you can use the .__name__
attribute of the returned type object, like so:

        number = 42
        num_type = type(number).__name__
        print(num_type)  # Output: int
        

Dealing With Custom Classes

If you’re working with custom classes or objects, the type() function works just as well. For
example, let’s define a simple class called Person and create an instance of it:

        class Person:
            def __init__(self, name, age):
                self.name = name
                self.age = age

        john = Person("John Doe", 30)
        print(type(john))  # Output: <class>
        

As you can see, the type() function returns the type of our custom class, including the module
it’s defined in (__main__ in this case). To get just the class name, you can use the
.__name__ attribute again:

        john_type = type(john).__name__
        print(john_type)  # Output: Person
        

Conclusion

Getting the type of a variable in Python is a simple and straightforward process using the built-in
type() function. This function works with both built-in data types and custom classes, making it
a versatile tool for understanding and working with Python variables. Remember to use the .__name__
attribute of the returned type object to get the actual type name as a string. Happy coding!