Suggesting for overloading the assign operator

Rim rimbalaya at yahoo.com
Tue Jul 1 05:31:47 CEST 2003


Hi,

I have been thinking about how to overload the assign operation '='.
In many cases, I wanted to provide users of my packages a natural
interface to the extended built-in types I created for them, but the
assign operator is always forcing them to "type cast" or coerce the
result when they do a simple assign for the purpose of setting the
value of a variable. Borrowing an example from this newgroup, the
second assignment below ereases all Currency knowledge from variable
'c', when the user only wanted to update the value of c, not its type:

c=Currency(5)
c=7

I fully understand the workaround of doing c=Curreny(7) instead, but
users don't want to be bothered with that.

I read some of the prior discussions, but I did not see a suggestion
for permanent a solution. I would like to propose the following.

The idea is to separate the value assignment from the type assignment,
by introducing a new operator, let's say the ':=' operator.

'=' remains what it is, assigns type and value at the same time
':=' assigns only the value

For example:

>>> class myint(int): pass
...
>>> a = myint()
>>> a := 6
type(a)
<class '__main__.myint'>
>>> a
6

In reality, := would just coerce the return type of the RHS of := to
the type of the variable on the LHS of the :=, preserving the value(s)
as best as it can.

If the type of the variable was still undefined, ':=' would behave
like '='. It might create confusion in future code, but does not break
old code.

I think it would be a nice feature to have. Comments?

Thanks,
- Rim




More information about the Python-list mailing list