Interview Kickstart has enabled over 21000 engineers to uplevel.
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:
The type() function allows you to return either of the following based on the arguments passed:
Two types of arguments can be passed into this function, they are:
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:
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.
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:
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:
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:
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.
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:
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.
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!
---------
Article contributed by Problem Setters Official
Attend our webinar on
"How to nail your next tech interview" and learn