What is Python's coerce() used for?
Solution 1
Its a left over from early python, it basically makes a tuple of numbers to be the same underlying number type e.g.
>>> type(10)
<type 'int'>
>>> type(10.0101010)
<type 'float'>
>>> nums = coerce(10, 10.001010)
>>> type(nums[0])
<type 'float'>
>>> type(nums[1])
<type 'float'>
It is also to allow objects to act like numbers with old classes
(a bad example of its usage here would be ...)
>>> class bad:
... """ Dont do this, even if coerce was a good idea this simply
... makes itself int ignoring type of other ! """
... def __init__(self, s):
... self.s = s
... def __coerce__(self, other):
... return (other, int(self.s))
...
>>> coerce(10, bad("102"))
(102, 10)
Solution 2
Python core programing says:
Function coerce () provides the programmer do not rely on the Python interpreter, but custom two numerical type conversion."
e.g.
>>> coerce(1, 2)
(1, 2)
>>>
>>> coerce(1.3, 134L)
(1.3, 134.0)
>>>
>>> coerce(1, 134L)
(1L, 134L)
>>>
>>> coerce(1j, 134L)
(1j, (134+0j))
>>>
>>> coerce(1.23-41j, 134L)
((1.23-41j), (134+0j))
Jzl5325
I am a research scientist working to apply spatial analysis, computer vision, and data mining techniques to planetary (Moon, Mars, Europa, etc.) data. My work focuses primarily on developing automated image matching techniques, developing tools for analyzing hyperspectral data, and the development of photogrammetric sensor models.
Updated on June 06, 2022Comments
-
Jzl5325 almost 2 years
What are common uses for Python's built-in
coerce
function? I can see applying it if I do not know thetype
of a numeric value as per the documentation, but do other common usages exist? I would guess thatcoerce()
is also called when performing arithmetic computations, e.g.x = 1.0 +2
. It's a built-in function, so presumably it has some potential common usage?