[Python-ideas] New __reference__ hook

haael at interia.pl haael at interia.pl
Tue Dec 4 10:58:04 CET 2012


Hi, guys.

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.

My proposal is to define another hook that gets called when an object is referenced.

def MyInteger:
	def __reference__(self, context):
		return copy.copy(self)

Each time when a reference count of an object would normally get incremented, this method should be called and the returned object will be referenced. The default implementation would be of course to return self. The context argument will give the object some information of the reason how we are being referenced.

This will allow easy implementation of such concepts as singletons, copy-on-write, immutables and even simplify things like reference loops.

The most obvious use-case would be implementations of some mathematical types like vectors, polynomials and so on. I've encountered this problem when I was writing a simple vector library and I had to explicitly copy each object on assignment, which is particulary annoying. The programmer's intuition for numeric-like types is for them to be immutable, yet they should have augmented asignment operators. This is a thing that can not be implemented transparently in the current Python, so there is my proposal.

Cheers,
haael.





More information about the Python-ideas mailing list