output formatting for user-defined types

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Apr 7 19:48:11 EDT 2006


On Thu, 06 Apr 2006 17:14:22 -0700, Russ wrote:

>>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.

How is this any more explicit and any less safe than:

dist = 4 * ft
print float(dist)

?


> What is unwise is to allow the conversion to happen
> automatically without the user's awareness. 

Who is talking about having conversions happen automatically without the
user's awareness? I certainly am not.

But in any case, I suspect you do automatically convert units. What do you
do in this case:

x = 45*ft
y = 16*m
z = x+y

Do you raise an error?


> That's where bugs creep in.

No, that is where ONE class out of an infinite set of possible bugs creep
in.

Go back to your original problem. You wanted to do something like this:

dist = 4*ft
some_string = '%f' % dist

You're converting a distance in feet to a string representation. This is
not only harmless, but vital. What are you worried about? That once you
provide a __float__ method for your classes, people will immediately
convert all their unit objects into raw floats and do all their
calculations on the raw floats? But as you point out, they can still do
that. It just takes them a tiny bit more work: a division instead of a
conversion.

All you are doing is making a rod for your own back, to no advantage.



-- 
Steven




More information about the Python-list mailing list