Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python coerce types when doing operator overloading?

Tags:

python

I have the following code:

a = str('5')
b = int(5)
a == b
# False

But if I make a subclass of int, and reimplement __cmp__:

class A(int):
    def __cmp__(self, other):
        return super(A, self).__cmp__(other)
a = str('5')
b = A(5)
a == b
# TypeError: A.__cmp__(x,y) requires y to be a 'A', not a 'str'

Why are these two different? Is the python runtime catching the TypeError thrown by int.__cmp__(), and interpreting that as a False value? Can someone point me to the bit in the 2.x cpython source that shows how this is working?

like image 882
Chris Avatar asked Sep 17 '12 18:09

Chris


People also ask

How does Python handle operator overloading?

The operator overloading in Python means provide extended meaning beyond their predefined operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class and "str" class.

Is Python support for operator overloading?

We can overload all existing operators but we can't create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator.

Why Python does not support method overloading?

When the runtime encounters another function with the same name it updates the entry in the local namespace and thus removes the possibility of two functions co-existing. Hence python does not support Function overloading.

What is the most popular form of operator overloading in python?

A very popular and convenient example is the Addition (+) operator. Just think how the '+' operator operates on two numbers and the same operator operates on two strings. It performs “Addition” on numbers whereas it performs “Concatenation” on strings.


1 Answers

The documentation isn't completely explicit on this point, but see here:

If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a __cmp__ method or rich comparison methods like __gt__, described in section Special method names.

This (particularly the implicit contrast between "objects of different types" and "objects of non-built-in types") suggests that the normal process of actually calling comparison methods is skipped for built-in types: if you try to compare objects of two dfferent (and non-numeric) built-in types, it just short-circuits to an automatic False.

like image 139
BrenBarn Avatar answered Oct 23 '22 12:10

BrenBarn