Assignement Overloading

John Roth johnroth at ameritech.net
Thu Jul 12 17:54:21 CEST 2001


"Pierre Denis" <Pierre-et-Liliane.DENIS at village.uunet.be> wrote in message
news:3b48bd83$0$7113$4d4efb8e at news.be.uu.net...
> I am trying to emulate some kind of type checking in Python
> (sorry for the heresy). Because of the dynamic typing, my unpretentious
> goal is to intercept the assignment statement in order to perform
> a consistency check between the variable and the object to assign.
> Unfortunately, there is no mechanism in Python to do this; there
> is no magic function like __assign__(name,value). The reason
> usually invoked about this lack is the fact that Python's assignment
> is actually just a name binding, which is very different, for
> instance, from C++ assignment.

Strong type checking is not a heresy. The subject comes up quite
frequently, and the general opinion seems to be that it would be a
good idea - as an option. The problem is that nobody has ever
proposed an acceptable way of accomplishing it.

The difficulty you're running into is that you've fixed on the idea of
solving one problem (lack of strong type checking) by using another
feature (overriding assignments) that turns out not to be there, either.

The only method of doing it is to use the __setattr__ function to
intercept all names in the objects you want to protect, and provide
a different method of accessing them.

> Now I have two questions :
>
> 1. Why is there no general way to overload the assignment in
> Python ? I do not agree with the 'name binding' argument because, to my
> humble opinion, __setattr__ allows to overload some assignments,
> while performing a name binding (in an object's namespace). So I
> think the problem is well stated and the request makes sense.

Assignment binds a name to an object. In C++ terms, all names are
declared as void *. An overloaded assignment would still have to return
an object. If I have an object, "spam", and I try to do this assignment:

breakfast = spam

what would you expect the spam object's __assign__ method to do with
an overload? And how would it do it? Or do you expect the name
"breakfast" to have an __assign__ method?

Also, you cannot use __setattr__ to influence the name binding of
local variables in a function or method.

If you can come up with a proposal, I'm sure it will be looked at. See
the PEP process for details. However, I know I would object if the
proposal stated "type checking" as a reason to do assignment overriding -
IMHO, type checking should be dealt with in a different manner.

John Roth

>
> Thanks in advance,
>
> Pierre Denis
>





More information about the Python-list mailing list