[Numpy-discussion] Possible new multiplication operators for Python

Andrew Dalke dalke@dalkescientific....
Sun Aug 17 18:50:36 CDT 2008


On Aug 18, 2008, at 12:00 AM, Ondrej Certik wrote:
> There is some inconsistency though, for example one can override A() +
> A(), but one cannot override 1 + 1. This could (should) be fixed
> somehow.

That will never, ever change in Python.  There's no benefit
to being able to redefine int.__add__ and doing so will break
entirely too many assumptions.

Here's one assumption - the C implementation does some
simple constant folding:

 >>> def f():
...   print 1+1
...
 >>> import dis
 >>> dis.dis(f)
   2           0 LOAD_CONST               2 (2)
               3 PRINT_ITEM
               4 PRINT_NEWLINE
               5 LOAD_CONST               0 (None)
               8 RETURN_VALUE
 >>>

With what you want that's not possible.


Just think of the implementation difficulty.  Are changes on the
per-module or per-scope or per-thread level?  And performance
would be lousy (or require deep inferencing analysis) because
every operation in C would need to go through the Python API
just in case some fundamental definition like this was changed.

Such a language is possible.  I wouldn't be surprised if
you could do it in Smalltalk and mostly do it in Ruby.  But
the general belief is that good design follows the
"open/closed principle":

   "software entities (classes, modules, functions, etc.)
   should be open for extension, but closed for modification"
          - Bertrand Meyer, quoted by
             http://en.wikipedia.org/wiki/Open/closed_principle

In Python, all types are closed for modification, and
while classes are open for modification it's highly frowned
upon to do so.  The name "monkey-patch" sounds somewhat
derisive for a reason.



				Andrew
				dalke@dalkescientific.com




More information about the Numpy-discussion mailing list