[Numpy-discussion] Possible new multiplication operators for Python

Ondrej Certik ondrej@certik...
Mon Aug 18 03:40:24 CDT 2008


On Mon, Aug 18, 2008 at 1:50 AM, Andrew Dalke <dalke@dalkescientific.com> wrote:
> 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.

Yeah, I understand the reasoning. My reason is that sometimes you want
to do something else on 1/2 rather than to get 0, or 0.5000000. I
would like to get my own class called, but if it's again Python, then
I am perfectly happy with Python as it is now. No changes needed.

Anyway, this is off topic.

Ondrej


More information about the Numpy-discussion mailing list