output formatting for user-defined types

Russ uymqlp502 at sneakemail.com
Sat Apr 8 04:26:43 EDT 2006


>So what you are saying is, if I enter a unit in feet, you automatically
>change that unit to some base unit (say, metres if you use SI) behind my
>back. So, assuming SI units as the base, if I say:

>print 2*ft + 1*ft

>you're going to give me an answer of 0.9144 metres, instead of the
>expected 3ft. Surely if I'm entering my values in a particular unit, I
>would like to see the answers in that same unit, unless I explicitly ask
>for it to be converted?

Actually, that was my initial thinking exactly, and it is exactly what
my first version actually did. I learned through experience, however,
that that approach makes adding differrent units of the same type
(e.g., feet and meters) substantially more complicated than it is using
my current approach,  so I abandoned it.

The disadvantage is that, as you point out, you can add feet to feet
and get meters. There are two answers to this problem. First, if you
expect to use feet consistently, you can easily make it your base unit.
Secondly, you can always convert the output to feet:

x = 2 * m
print format(x,ft)

That may seem inconvenient, but there are actually a couple of
significant advantages here that makes this form preferable to simply
"print x". One advantage is that if you "disable" units for efficiency,
your output can (and will) still show the units of feet. Otherwise you
lose the unit information completely. The other advantage is that you
can change your base unit and your program will still produce the same
result.

>sin(45*ft)

>is still an error.

>sin(45)

>shouldn't be, even if that 45 came from float(45*ft). What do you care
>where the value comes from? I'm sure you allow sin(float('45')) without
>complaining that trig functions don't operate on strings.

Either you don't understand how the "__float__" function works or you
don't understand basic physics. If the float function converts 45 * ft
to simply 45, then sin(45*ft) will be automatically converted to
sin(45). That is most definitely *not* what you want.

>So, despite your going on about the evils of automatic conversions behind
>the user's back, you do go ahead and do automatic conversions behind the
>user's back.

>Slight inconsistency, don't you think?

Let's try this one more time. Automatic conversion is fine as long as
the conversion is dimensionally correct. Automatically converting from
feet to a dimensionless number is *not* dimensionally correct. This
isn't rocket science.

>Hey, it isn't *me* battling to find a way to easily print my instance
>objects.

Actually, I have already developed an excellent workaround for that
problem.

By the way, I doubt you are impressing anyone here. Are you sure you
want to continue with this?




More information about the Python-list mailing list