[Python-ideas] New __reference__ hook

Mike Graham mikegraham at gmail.com
Wed Dec 5 15:10:14 CET 2012


On Tue, Dec 4, 2012 at 4:58 AM, <haael at interia.pl> wrote:

>
> Python 3 is very close to become a holy grail of programming languages in
> the sense that almost everything could be redefined. However, there is
> still one thing missing: the immutable copy-on-assign numeric types.
> Consider this part of code:
>
> a = 1
> b = a
> a += 1
> assert a == b + 1
>
> The object "1" gets assigned to the "a" variable, then another independent
> copy gets assigned to the "b" variable, then the value in the "a" variable
> gets modified without affecting the second.
> The problem is - this behaviour can not be recreated in user-defined
> classes:
>
> a = MyInteger(1)
> b = a
> a += 1
> assert a == b + 1
>
> The "a" and "b" variables both point to the same object. This is a
> difference on what one might expect with numeric types.
>

You misunderstand Python's semantics. Python never implicitly copies
anything. Some types, like int, are immutable so you can't distinguish
meaningfully between copying and not.

All names like `a` can be rebound `a = ....`, and this never mutates the
object. Some objects can be mutated, which is done by some means other than
rebinding a name.

I don't know what problem you had defining MyInteger. Here is a definition
(albeit comprised of very, very sloppy code) that passes your test

class MyInteger(object):
    def __init__(self, i):
        self._i = i

    def __add__(self, other):
        if isinstance(other, MyInteger):
            other = other._i
        return MyInteger(self._i + other)

    def __eq__(self, other):
        return self._i == other._i

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20121205/dd063981/attachment.html>


More information about the Python-ideas mailing list