Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Python's coerce() used for?

Tags:

What are common uses for Python's built-in coerce function? I can see applying it if I do not know the type of a numeric value as per the documentation, but do other common usages exist? I would guess that coerce() 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?

like image 966
Jzl5325 Avatar asked Jan 23 '13 18:01

Jzl5325


People also ask

What is coerce in Python?

Remarks. Coercion is the implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type.

Does Python have coercion?

Many programming languages have something called type coercion; it's where the language will implicitly convert one object to another type of object in certain circumstances. Python does not have type coercion.


1 Answers

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) 
like image 117
Greg Bowyer Avatar answered Sep 17 '22 12:09

Greg Bowyer