top

Search

Python Tutorial

.

UpGrad

Python Tutorial

type() function in Python

Introduction

Type in Python is a built-in function that returns the type of a given object stored in a variable. It is used for debugging purposes and creates a class dynamically within selected objects. We use type in Python to find out what type the object is and return parameters of given objects. It is a very straightforward function, easy to use, and is used mostly in metaprogramming practices, being especially valuable in libraries where new classes have to be made. Today, we will cover everything you need to know about type in Python below.

Overview

Type() is a simple function that tells the developer what type of value a variable holds. If a variable contains a value of 5.95 and uses type() on it, it will return the result as float. Another example is if a variable 'subj' has the word 'Python' and uses type(subj) on it, then the type returned for the value would be a string. Data type in Python can be integers, strings, floats, tuples, etc.

type() can be used to determine what type of object is declared within a variable. There are 2 types of parameters that can be passed onto type(). The first is a single parameter and the second is a type() function with 3 parameters. type() is used to return data type in Python function with the outputs and works on multiple variables.

Python type() function Syntax

The syntax of the type() function Python is as follows:

type(object)

type(name, bases, dict)

A single argument is passed on the type() function in Python to display the type of only one object. If multiple arguments are passed, type() will return the newest object. type() can take up to 3 object parameters which are - name, bases, and dict. The name parameters return the class name while the bases attribute specifies the base classes. Bases is similar to _bases_. The dict attribute in Python is the same as _dict_ and returns dictionary objects from specified key-value pairs.

Examples of the type() function in Python

Let's check out a few examples of how the type() function works in action when new arguments are passed.

Example 1 - Finding out the class type of a variable 

prime_numbers = [8, 9, 1, 2] 
# check type of prime_numbers
result = type(prime_numbers)
print(result) 
# Output: <class 'list'>

Explanation:

In the above type() function in Python example, type() will return the type of object based on the new arguments passed. The programmer created a variable called 'prime_numbers' and used the result to find out the type of the variable. When the user runs the output, the console will print the output <class 'list'> because the type of variable is a list. 

Example 2 - Finding out the type of a Python object

x = 10
print(type(x))
 s = 'abc'
print(type(s))

from collections import OrderedDict 
od = OrderedDict()
print(type(od))

class Data:    pass
 d = Data()
print(type(d))

Output:

<class 'int'>
<class 'str'>
<class 'collections.OrderedDict'>
<class '__main__.Data'>

Explanation:

The type() function will return the module name along with the type of an object. In this example, the Python script doesn't have a module which is why it returns the module as _main_.

Example 3 - Return the type of different objects

a = ('apple', 'banana', 'cherry')
b = "Hello World"
c = 33
x = type(a)
y = type(b)
z = type(c)

Output:

<class 'tuple'>
<class 'str'>
<class 'int'>

Explanation:

type() was used to identify the objects stored in variables a,b, and c. x,y, and z variables were used to store the results for type() function. When the user printed the output, it returned 'a' as tuple (a list), 'b' as string, and 'c' as integer.

Example 4: Creating a class dynamically with type()

Let's say we want to create two classes. The first class will be about a car 'Porsche' and it will contain attributes such as non-electric and have a speed of 100. A second class will be named 'Tesla' and Tesla will be an electric car that is faster than Porsche, preferably having a speed of 110.

Here is how we would dynamically create these classes with type().

porsche = type('Car', (object,), {speed: 100, 'electric': False})
tesla = type('Car', (object,),{speed: 110, 'electric': True})

If we type porsche for the output, the class would be returned as <class '_main_.Car'>

porsche.speed would give us a result of 100

porsche.electric would return false

tesla.speed would give us 110

tesla.electric would return true

Notice how we didn't have to create a separate class MyCar and define individual attributes within the braces. We used type() to predefined classes within a single line of code. This is how powerful type() is and it saves programmers a lot of time! It's important to note that type() can take between 1 or 3 arguments. There are 2 arguments and 4 or more arguments are not supported. The first argument is the name of a class being created, the second is the base form which your other classes will inherit, and finally, the third is the dictionary attribute that holds methods and variables inside classes.

Example 5: Pulling metadata details from classes

Let's say we want to pull metadata from Python classes and extract the bases, dict, doc properties, and Python type class. We can write a class, define attributes, and print the properties of those classes. Type() can be used to make similar classes and extract those details directly.

Here's how to go about it.

Step 1: Create the class

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

Step 2: Print the class

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

Step 3: Print properties of said classes

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

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

We will get this output:

<class 'type'>
(<class 'object'>,)
{'__module__': '__main__', '__doc__': 'Data Class', 'd_id': 10, '__dict__': <attribute '__dict__' of 'Data' objects>, '__weakref__': <attribute '__weakref__' of 'Data' objects>}
Data Class 
<class 'type'>
(<class '__main__.Data'>,)
{'__module__': '__main__', '__doc__': 'SubData Class', 'sd_id': 20}
SubData Class

Step 4: Create similar classes using type() and print them for faster results

Data1 = type('Data1', (object,), {'__doc__': 'Data1 Class', 'd_id': 10})
SubData1 = type('SubData1', (Data1,), {'__doc__': 'SubData1 Class', 'sd_id': 20})

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

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

The output for the type() function will be as follows:

<class 'type'>
(<class 'object'>,)
{'__doc__': 'Data1 Class', 'd_id': 10, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Data1' objects>, '__weakref__': <attribute '__weakref__' of 'Data1' objects>}
Data1 Class 
<class 'type'>
(<class '__main__.Data1'>,)
{'__doc__': 'SubData1 Class', 'sd_id': 20, '__module__': '__main__'}
SubData1 Class

Type() can be used in versatile ways but remember that we cannot make functions in the dynamic class using type() in Python.

Example 6: Recreating Movie class with type()

We know that it can instantiate a class in Python and have its own. The Movie class can have a higher class above it. Let's create the class.

class Movie:

    def __init__(self, rating, genre):
        self.rating = rating
        self.genre = genre
    def show_characteristics(self):
        characteristics = [self.genre, self.rating]
        return characteristics

Now, what happens if we choose to inspect the object in class Movie using type()?

print(type(Movie))

We will get the output <class 'type'>. If we try to execute type() on any string, integer, or other Python classes within the class, we will still get the output as <class 'type'>. It's because the Python type hints class is the parent and all classes and objects inherit everything from it.

If we are to recreate the Movie class using type(), here is how we would do it:

def movie_init(self, genre, rating):
    self.genre = genre
    self.rating = rating
def show_characteristics(self):
    characteristics = [self.rating, self.genre]
    return characteristics
movie_class = type("MovieClass", (), {"__init__": movie_init, "show_characteristics": show_characteristics})

Our Movie class will not inherit from any other class which is why the base class is left void (empty tuple). The init and show_characteristics are methods we have created  because it can be challenging to fit them within the dictionary.

What we end up with is a movie_class that we can use.

Let's see it in action.

movie = movie_class("10", "horror")
print(movie.show_characteristics())

Output:

['10', 'horror']

Python type() with 3 Parameters

Let's see what happens when we pass 3 parameters to type().

# Python type() function when three arguments are passed  
BaseClass = type(' BaseClass ', (), { 'a' : 100})  
print(type(BaseClass))

Output:

<class 'type'>

In this case, we have created a new class called BaseClass and assigned 3 arguments to it. A void tuple was used to define that there are no base classes and the dictionary attributes were set to a word 'a' having a value of 100. We have printed the print type Python of the class BaseClass using the type() function and it returned the result as <class 'type'>.

type() Function Applications

  • Python type() function can be used to create tables in MySQL databases

  • In Python, we store objects in classes and use them in different parts of the code. The type() function eliminates the need to create separate classes by dynamically creating classes in the code. It defines attributes during the runtime of programs and can pass up to 3 arguments

  • In Python, it is a common practice to not define the variable by default. Programmers create variables and store values in them. The type() function identifies the Python type string of values in these variables and classifies them. It is really useful for debugging cases

  • type() can be used to define the blueprint for different classes and even set rules for these classes. It helps understand the behaviors of different objects in classes

Conclusion

The type() function can be used to find out the type of object stored in Python variables or create new classes dynamically. It can take between one to three arguments and is helpful for programmers.

FAQs

1. What are the different ways of writing the type() syntax?

There are only 2 ways of using the type() syntax: type(object) and type(name,base,dict)

2. What is the use of type() in Python programming?

type() is a pre-built function that describes the type of data stored in variables. It can also be used to dynamically create classes and assign attributes to them in the code.

3. What are Python tuples in type()?

Python tuples associated with the type() functions are similar to lists. Tuples are immutable and cannot be changed once created. They are used for storing constants and useful in cases such as maintaining database records which cannot be modified. 

Leave a Reply

Your email address will not be published. Required fields are marked *