aleax at aleax.it
Thu Sep 26 09:32:45 EDT 2002
James J. Besemer wrote:
>>(I favor the
>>latter definition, since it carries more information about the
> It doesn't really tell you anything.
> Else, in 25 words or less, why does Perl's "+" operator supposedly work
> the one way and Python's "*" operator work the other way?
Perl's + *creates a numeric context*: operands implicitly "become numbers".
Python's x*y calls x.__mul__(y) or else y.__rmul__(x) -- no "context",
nothing "becomes", _objects_ drive.
There -- 24 words by wc's count, so, little space to insert caveats
about implementation quirks &c, such as optimizations which e.g. *
could insert for types it knows about -- conceptually, everything
should work as if operators were implemented by dispatching special
methods, although optimization with invariant program-observable
results is clearly fine; and the like.
I have to agree with you that Perl's overall defined behavior CAN
be implemented by mechanisms akin to Python's (don't know if it
IS -- my knowledge of Perl's internals dates to Perl 4, and back
then, as I recall, it wasn't); but the mental model becomes too
cumbersome that way -- in practice, thinking in terms of various
established-contexts is just about inevitable in Perl (some of
them you can even TEST for, e.g. via wantarray). Python's own
overall defined behavior OTOH is most simply conceived by seeing
operators as syntax sugar for templates (in the sense of the
"template method" DP -- they aren't methods, but they're templates
in just that way), involving one or more calls to the operands'
special methods. Stringification does involve "implicitly become"
(via __str__ or __repr__, but that's really no more than "giving
context" as in so many cases in Perl) -- the print statement, and
the % operator with string LHS, being the two cases. One could
quibble about "boolean contexts" (in statements if and while,
and operators and, or, not) -- arguing that there's a "become"
there, however, is denied by the fact that and and or return one
of their two operands, without having made it become anything,
so I don't think __nonzero__ is best considered a "become" special
method here (but I can see the arguments on the reverse side,
since it IS quite natural to speak of "truth context" and the
like to explain this little part of Python).
More information about the Python-list