Open In App

Return True if Cast Between Data Types can Occur According to the Casting rule in Python

Last Updated : 30 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see that if the program returns True if the case between different data types can occur according to the casting rule of Python.

Casting Rules in Python

In Python, the term “casting” refers to the method of converting one datatype into another. In Python, there are certain built-in data types amongst which we can cast, they are int(), bool(), str() and float(). Apart from that, there are certain basic principles of this casting rule in Python, which are mentioned below.

  • Implicit Casting / Type Coercion – Python supports this feature automatically, in this type of casting, Python automatically casts a data type into another safely, without raising any error or human intervention. For example – In Python, if we try to add an int with a float the result will be in float. Here Python simply cast the result into different data types without any error or human intervention.
  • Explicit Casting – Here we need some human intervention, developers need to explicitly cast a data type into some other. Python will not do this automatically. Developers can explicitly use functions like int() to cast any supported value into Integer type, float() to cast in float type, etc.
  • Type Compatibility – This means that we can’t implicitly or explicitly cast anything into another type. Only supported and compatible types can be cast amongst each other. Example – It is possible to cast int() into float and vice versa, but we can’t explicitly or implicitly convert a string (text) into an integer.
  • Precision Loss – This happens when we try to cast a float into an integer. The decimal part of the number gets truncated, which decreases the precision of the number.

Check Casting without using Module

In this example, we will not use any built-in or external module to find out if the casting is possible or not. We will only use the try-catch block.

We will first create a function that takes two parameters, one for the type from which we want to convert and the other one is the type in which we are trying to cast. Then we will try to temporarily cast the source type into the destination type by creating an instance of the destination type and passing the source type as its argument.

We will create an instance of the source type and try to cast it to the destination type by passing that as the parameter of the destination type. If we don’t get any error then we will simply print True, otherwise in the except section we will check if we are getting any value error or not, which signifies that we can’t cast that. In that case, we will return False. We are using a try-except block just to make sure our program doesn’t stop in between due to an error.

Python3




# Function to check if casting is possible or not
def can_cast(source_type, dest_type):
    try:
        dest_type(source_type())
        return True
    except ValueError:
        return False
 
# Driving Code
print(can_cast(int, float)) 
print(can_cast(float, int)) 
print(can_cast(str, int))   
print(can_cast(int, str))   
print(can_cast(float,str))
print(can_cast(str,float))


Output

True
True
False
True
True
False

Check Casting using numpy.can_cast() Method

There is a method of the NumPy module called can_cast(). This method takes two arguments and checks that is it possible to cast it from the former to the latter.

Syntax of can_cast()

numpy.can_cast(source_type,destination_type)

Example: In the code, we have used certain strings like i8,f8,i4, S4, etc. These are string representations of some data types which are explained below.

  • i8 – It represents int64 i.e. 64-bit integer.
  • f8 – It represents float64 i.e. 64-bit float.
  • i4 – It represents int32 i.e. 32-bit integer.
  • S4 – It represents a simple string whose length is 4.

Python3




import numpy as np
 
# Define a list of data types to test casting
data_types = [
    np.int32,
    np.float64,
    complex,
    'i8',
    'f8',
    'i4',
    'S4'
]
 
# Perform casting checks for each pair of data types
for i in range(len(data_types)):
    for j in range(i+1, len(data_types)):
        source_type = data_types[i]
        destination_type = data_types[j]
        res = np.can_cast(source_type, destination_type)
        print(f"Can cast {source_type} to {destination_type}: {res}")


Output:

Can cast <class 'numpy.int32'> to <class 'numpy.float64'>: True
Can cast <class 'numpy.int32'> to <class 'complex'>: True
Can cast <class 'numpy.int32'> to i8: True
Can cast <class 'numpy.int32'> to f8: True
Can cast <class 'numpy.int32'> to i4: True
Can cast <class 'numpy.int32'> to S4: False
Can cast <class 'numpy.float64'> to <class 'complex'>: True
Can cast <class 'numpy.float64'> to i8: False
Can cast <class 'numpy.float64'> to f8: True
Can cast <class 'numpy.float64'> to i4: False
Can cast <class 'numpy.float64'> to S4: False
Can cast <class 'complex'> to i8: False
Can cast <class 'complex'> to f8: False
Can cast <class 'complex'> to i4: False
Can cast <class 'complex'> to S4: False
Can cast i8 to f8: True
Can cast i8 to i4: False
Can cast i8 to S4: False
Can cast f8 to i4: False
Can cast f8 to S4: False
Can cast i4 to S4: False

Now why we are using those representations rather than normally using int64,int32, etc? Because the can_cast() method of Numpy doesn’t just take those direct values but also understands this kind of short representation. To demonstrate that we are using these representations.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads