output formatting for user-defined types

Russ uymqlp502 at sneakemail.com
Thu Apr 6 20:14:22 EDT 2006


>I'm sorry, your system of units doesn't allow trig functions to operate on
>degrees? I presume you don't allow grads either. What about steradians or
>other arbitrary measures of angle or solid angle?

I should have stated that more clearly. You can enter the value in
degrees, but it will automatically get converted to radians for
internal use. When you pass it to a trig function, it will
automatically be in radians. For example:

>>> angle = 30 * deg
>>> print sin(angle)
0.5

You could force it to maintain degrees internally if you wanted to, but
then you couldn't pass it to a trig function. That little feature
prevents perhaps the most common unit error, passing degrees when
radians are expected.

I once heard about a simulation that was run for six months before the
researchers realized that their results were corrupted by such an
error. Yes, that's an extreme case, and maybe they were nitwits (with
Ph.Ds), but these errors are very commonplace and often costly in terms
of corrupted results or debugging time. And who knows how many times
such errors subtly corrupted results but were never even detected?

If you want to print it out in degrees, you must explicitly specify
degrees, then it will get converted to degrees for output. For example:

>>> angle = 30 * deg
>>> print >> format ( angle, "deg", "%4.2f" )
30.00 deg

That may seem inconvenient, but it actually helps when the units are
turned off for efficiency, because then the units are still known and
can be printed out explicity.

>(3) You're not my mother. If I want to shoot myself in the foot by
>extracting the scalar part of one of your precious units and then doing
>inappropriate things to it, that's absolutely none of your business.

I am developing a way to guard against common errors in scientific and
engineering software. If you want to use it, then don't. I work in air
traffic control, so I am very concerned about such errors. [No, we
don't use Python for actual operational ATC, but I use it for
prototyping and data analysis. Nevertheless, I believe in avoiding
errors anyway.]

>I suggest another approach: play nice with the rest of Python by allowing
>people to convert your units into strings and floats. Once they have
>explicitly done so, it isn't your problem if they want to add 35 metres to
>18 kilograms and convert the answer into minutes.

Converting to a float is a trivial matter of dividing by the units of
the scalar. For example:

>>> dist = 4 * ft
>>> print >> out, dist/ft
4

Note, however, that this requires the user to explicity ask for the
conversion. What is unwise is to allow the conversion to happen
automatically without the user's awareness. That's where bugs creep in.




More information about the Python-list mailing list