Understanding the type() Function in Python for Beginners

Last updated by Dipen Dadhaniya on Dec 21, 2024 at 06:17 PM
Contents

In programming, there are various types of data that a software engineer can come across. Some important data types include numeric, string, and Boolean. In the process of building software or a product, it is essential to understand the type of data that you are dealing with. There are various built-in functions that allow you to understand the behavior and functionality aspects of data.

This article will take you through one such built-in function that returns the type of data that you are working with:

  • What is the type() function?
  • How type() works with different data types
  • Extracting details from Python classes
  • Difference between isinstance() and type()
  • Real-life applications of the type() function
  • FAQs on Python’s type() function

What Is the type() Function?

The type() function allows you to return either of the following based on the arguments passed:

  • Type of object
  • New type object

Two types of arguments can be passed into this function, they are:

  • Single argument (returns Type of an object)
  • Three argument (returns an object of a new type)

Single-argument type() Function

If a single argument type is passed, then it returns the type of the provided object.

Syntax:

Example:

# Creating a function that returns the type

def dataType(i):

return “The data type of {} is {}”.format(i, type(i))

# List

list_num = [1, 4, 3, 4, 2, 1]

# Tuple

tuple_char = “ABC”

# Dictionary

dict_country = {“India”: “Delhi”, “America”: “Washington”}

result1 = dataType(list_num )

result2 = dataType(tuple_char )

result3 = dataType(dict_country )

# Printing the results

print(“-“, result1)

print(“-“, result2)

print(“-“, result3)

Result:

Three-argument type() Function

If three argument types are passed, then it returns a new type object.

Syntax:

The bases parameter is a tuple of classes from which the current class derives, whereas dict is a dictionary that represents all methods and fields defined in the class. The use case for type(name, bases, dict) is when you want to dynamically generate classes at runtime. In other words, the bases specify the base classes, and dict allows you to create the class body.

Example:

# type(name, bases, dict)

codingInterview = type(“Python”, (object,), dict(a=”Round”, b=1))

# Printing the type

print(type(codingInterview))

# Printing the __dict__ attribute

print(vars(codingInterview))

Result:

Here, the vars() function returns the __dict__ attribute. This attribute is used to store an object’s writable attributes.

Note: You can change the attributes if required.

How type() Works With Different Data Types

You can create a list that contains different types of data types. Then, you can identify the data type of each element in the list using a for loop. This is performed in the following code:

collection = [13, “Alice”, (3, 5), 88.9645, [“a”, “b”, “c”]]

for elements in collection:

print(“Elements: {}—> Type: {}”.format(elements, type(elements)))

Result:

TextDescription automatically generated

Extracting Details From Python Classes

Consider the following classes. You pull the metadata about the classes using the class, bases, dict, and doc properties as shown:

Note: The doc properties represent string literals that are present just after the definition of a function, module, class, or method.

# Parent class

class class1:

“””A class called class1″””

x = 10

# Child class

class subclass1(class1):

“””A subclass of class1″””

y = 20

You can print the properties of these classes using the following code:

# Printing the properties of these classes without using type

print(class1.__class__)

print(class1.__bases__)

print(class1.__dict__)

print(class1.__doc__)

print()

print(subclass1.__class__)

print(subclass1.__bases__)

print(subclass1.__dict__)

print(subclass1.__doc__)

Result:

However, writing such a code is tedious. Instead, this can be performed using the type() function.
For class1, its properties can be displayed using three arguments. The following code performs this easily:

infoAboutClass1 = type(“class1”, (object,), {“__doc__”: “A class called class1”, “x”: 10})
print(vars(infoAboutClass1))

Here, you are using the three arguments to return a new type object. Previously, you declared the __doc__ separately but using the type() function, you can perform this in just one line of code.

Result:

For class2, a similar approach can be followed. The code to perform this is as follows:

infoAboutClass2 = type(“Class2”, (object,), {“__doc__”: “A subclass of class1”, “y”:20})
print(vars(infoAboutClass2))

Result:

Difference Between isinstance() and type()

The type() function only returns the type of an object whereas, the isinstance() function checks more than that.

Example:

numbers = [1, 2, 5, 3]

# Using type

print(“Using the type function”)

print(type(numbers))

print(“——“)

# Using isinstance

print(“Using the isinstance function”)

print(isinstance(numbers, list)) 

Result:

TextDescription automatically generated

Real-life Application of the type() Function

There are various instances where you can use this function in your application. Here, we’re taking a simple application of type() in calculators (along with isinstance()).

Example:

def calculate(num1, num2, operation=’sum’):

“””

– Creating a function that takes two numbers and performs four operations

– By default, it will perform addition

“””

if not(isinstance(num1, int) and isinstance(num2, int)):

print(f’Invalid types of arguments – num1:{type(num1)}, num2:{type(num2)}’)

raise TypeError(‘Incompatible types of arguments!’)

 # Operations

if operation == ‘Difference’:

return num1 – num2

if operation == ‘Multiply’:

return num1 * num2

if operation == ‘Divide’:

return num1/num2

return num1 + num2

a = “hello world”

calculate(a, 5, “Multiply”)

Result:

Invalid types of arguments – num1:<class ‘str’>, num2:<class ‘int’>
Traceback (most recent call last):
File “C:/Users/HP/Desktop/InterviewKickstart/dummy/test.py”, line 23, in <module>
calculate(a, 5, “Multiply”)
File “C:/Users/HP/Desktop/InterviewKickstart/dummy/test.py”, line 8, in calculate
raise TypeError(‘Incompatible types of arguments!’)
TypeError: Incompatible types of arguments!

The inputs to the calculator are checked if they are not integer values. If they are, then the specified operation is performed. Otherwise, a TypeError is thrown.

FAQs on Python’s type() Function

Question 1: What is the difference between the type function and the different types of functions?
Answer: The type function returns the class type of a variable that is provided as an input. On the other hand, Python has different types of functions such as built-in, user-defined, etc.

Question 2: What are the data types in Python?
Answer:
Python has five basic categories of data types — Text,  Numeric, Sequence, Mapping, Set. Following are the data types under each category:

  • Text: Str
  • Numeric: Int, float, complex
  • Sequence: List, tuple, range
  • Mapping: Dict
  • Set: Set

Question 3: Is it mandatory to use type() with base and dict parameters?

Answer: No. “name” is the only parameter that is mandatory and that you are required to pass in the type() function.

Preparing for a Tech Interview?

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview preparation, we have trained thousands of engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

———

Article contributed by Problem Setters Official

 

Last updated on: December 21, 2024
Author
Dipen Dadhaniya
Engineering Manager at Interview Kickstart
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC