How python internally identify data type of an object?


In above code Python will not allow addition of int object with string object but it will allow integer addition with float object …So I want to know how python identify the difference in numeric and sequence data types

If you type (responses included):

<class 'int'>

<class 'str'>

<class 'float'>

Python ‘knows’ and ‘identifies’ the differences.

But on to ‘how’ Python ‘knows’, perhaps if Python detects a period ‘.’ after an integer, then it determines that it is a float. If there are no periods in a number, then it must be an integer. If it detects opening and closing quotes, then it determines that it must be a string, even if: ‘3454’, for example.

As indicated in the first answer, the type function is used to check the types of the two objects to add, and determine if the addition is allowed/defined. The check is performed in the __add__ method.

From the official documentation (3. Data model — Python 3.12.1 documentation) of the __add__ method:

For instance, to evaluate the expression x + y, where x is an instance of a class that has an __add__() method, type(x).__add__(x, y) is called. (…) If [the __add__()] method does not support the operation with the supplied arguments, it should return NotImplemented.

There is nothing to “identify”. Every object stores information about its own type, and each type can have its own code for operators, and the operation works or does not work according to whether there is code provided fro it.

Paul described part of how Python decided what type of object to make from code. When it does so, it stores the type/class itself as the object’s __class__ attribute.

>>> n = 1
>>> n.__class__
<class 'int'>
>>> n.__class__ is int
>>> c = 'a'
>>> c.__class__
<class 'str'>