Inefficiency of __getattr__

Kragen Sitaker kragen at dnaco.net
Mon Oct 2 13:52:18 EDT 2000


In article <slrn8tggpc.572.hzhu at localhost.localdomain>,
Huaiyu Zhu <hzhu at users.sourceforge.net> wrote:
>However, I'm not sure how is __coerce__ supposed to work.  The documentation
>has just a very terse description:
>
>coerce (x, y) 
>      Return a tuple consisting of the two numeric arguments converted to a
>      common type, using the same rules as used by arithmetic operations.
>
>Does this mean
>
>    a+b == apply(a.__class__.__add__, a.__coerce__(b))
>
>None of my three books mention coerce.

Yes, I think so, although I think it uses the __add__ from the first
element of the tuple, not from a.

Keep in mind that automatic type coercions are really evil; they are
partly justified for numeric types, but I'm reluctant to have them even
there.  The problem is that their presence vastly increases the number
of possible ways to misunderstand your program.

One of Python's biggest advantages over Perl is that it doesn't have
automatic conversion between strings, lists, hashes, and references;
between integer and floating-point; or between strings and numbers.
Many, many times I've fed Perl a program that was utterly nonsensical
(subtracting references from numbers, for example; a particularly
egregious case, because if you coerce a reference first to a string,
then to a number, you get 0, but if you coerce it straight to a number,
you get a unique number, like Python's id()) and had it run and produce
wrong results.

Every time I've argued static versus dynamic typing with a
static-typing fan, they've ended up concluding that what they really
hate is not dynamic typing but silent coercions.
-- 
<kragen at pobox.com>       Kragen Sitaker     <http://www.pobox.com/~kragen/>
Perilous to all of us are the devices of an art deeper than we ourselves
possess.
                -- Gandalf the Grey [J.R.R. Tolkien, "Lord of the Rings"]





More information about the Python-list mailing list