classification
Title: "x / 1" and "x * 1" should return x
Type: performance Stage:
Components: Interpreter Core Versions: Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: mrjbq7, rhettinger
Priority: normal Keywords:

Created on 2009-08-11 16:44 by mrjbq7, last changed 2009-08-11 16:56 by rhettinger. This issue is now closed.

Messages (2)
msg91479 - (view) Author: mrjbq7 (mrjbq7) Date: 2009-08-11 16:44
There are a couple arithmetic operations that idempotent, where the 
returned python object is the same python object as the input.  

For example, given a number:

>>> x = 12345

The abs() builtin returns the same number object if it is already a 
positive value:

>>> id(x)
17124964
>>> id(abs(x))
17124964

The "multiply by zero" operation returns a single "zero" object:

>>> id(x * 0)
16794004
>>> id(x * 0)
16794004

But, the "multiply by 1" or "divide by 1" does not:

>>> id(x * 1)
17124928
>>> id(x * 1)
17124880
>>> id(x / 1)
17203652
>>> id(x / 1)
17124952
msg91480 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2009-08-11 16:56
Sorry, Python makes no guarantees about object identity for numbers, so
this is just an optimization request.  While it could save a little
space (one number object) and a little time (for allocating that
object), the special casing imposes a small (but non-zero) cost on every
other case for multiplication and division -- optimizing one corner case
at the expense of the general case.

* practicality beat purity
* special cases are not special enough ...
History
Date User Action Args
2009-08-11 16:56:40rhettingersetstatus: open -> closed

type: performance
assignee: rhettinger

nosy: + rhettinger
messages: + msg91480
resolution: not a bug
2009-08-11 16:44:57mrjbq7setcomponents: + Interpreter Core
versions: + Python 2.6
2009-08-11 16:44:29mrjbq7create