Lazy coerce function?

Martin von Loewis loewis at informatik.hu-berlin.de
Mon Sep 25 17:36:07 EDT 2000


Treutwein Guido <Guido.Treutwein at nbg.siemens.de> writes:

> The documentation is a little bit on the short side, specifying, that
> numbers are casted to compatible types.
> 
> Python 1.6 reacts as follows:
> coerce(3,'a') # raises a TypeError, as expected.
> coerce('a', 'b') # returns ('a', 'b')
> coerce('a', []) # raises TypeError
> 
> Is there any simple rule under what circumstances coerce raises an
> exception?

The results of coerce are typically passed to arithmetic
operations. If there is some sensible way to convert the arguments
that the results support arithmethic operators, the conversion is
performed - otherwise you get a type error.

A good candidate operator is '+': if plus 'ought to' work on the
operands, coerce will return objects that can be added. That's why
coercing strings and lists does something nontrivial.

Regards,
Martin



More information about the Python-list mailing list