Adaptation and typecasting (was Re: [Python-Dev] replacing
Phillip J. Eby
pje at telecommunity.com
Tue Oct 28 21:31:53 EST 2003
At 02:37 PM 10/29/03 +1300, Greg Ewing wrote:
>"Phillip J. Eby" <pje at telecommunity.com>:
> > For a protocol p that has immutability as part of its contract,
> > adapt(x,p) is well within its rights to return an object that is a
> > "copy" of x in some sense.
>I don't think that's right -- this should only apply if
>the original object x is immutable. Otherwise, changes to
>x should be reflected in the view of it provided by p --
>even if p itself provides no operations for mutation.
There's a difference between an interface which provides no methods for
mutation, and an interface that *requires* immutability. Part of the
concept of an 'int' or 'tuple' is that it is a *value* and therefore
unchanging. Thus, one might say that IInteger or ITuple conceptually
derive from IValueObject.
However, that doesn't mean we can't say that adapt([1,2,3],tuple) should
fail, and I'm certainly open to the possibility of such an interpretation,
if it's decreed that supporting 'tuple' means guaranteeing that the adaptee
doesn't change state, not merely the adapted form.
It seems there are three levels of "immutable" one may have in an
1. No mutator methods, but no requirements regarding stability of state
2. Immutability is required of the adapted form (snapshot)
3. Immutability is required of the adaptee
I have made plenty of use of cases 1 and 2, but never 3. I'm having a hard
time thinking of a use case for it, so that's probably why it hasn't
occurred to me before now. Looking at this list, I now understand at least
one of Alex's points better: he (and I think you) are assuming that an
immutable target protocol means case 3. That has been baffling the heck
out of me, because I have not yet encountered a use case for 3.
On the other hand, it's possible that I *have* seen use case 3, and
mistaken it for use case 2, simply because all the types I wrote adapters
for were immutable.
Given all this, I think I'm okay with saying that adapting from a mutable
object to an immutable interface (e.g list->tuple) is an improper use of
adaptation. Presumably this also means StringIO->str adaptation would be
invalid as well. But, int<->str and other such immutable-to-immutable
conversions seem well within the purview of adaptation.
More information about the Python-Dev