output formatting for user-defined types

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Apr 6 19:39:21 EDT 2006


On Thu, 06 Apr 2006 11:05:06 -0700, Russ wrote:

>>Really, your response seems a little bizarre to me, given that __float__
>>is the defined way in which float() gets a value from an instance, and
>>float() is what the % operator calls when it encounters a '%f' in the
>>format string.
> 
> My class represents physical scalars with units. If I allow arbitrary
> conversion to float, then the user can pass any units to trig
> functions. But trig functions expect radians, so passing any other unit
> (e.g., degrees or meters) is an error. 

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?

Sounds like an awfully limited system of units to me.


> To prevent such errors, I allow
> conversion to float only when the units are actually radians (or
> dimensionless). That is just one of several reasons for preventing
> arbitrary conversion to float, but I won't go into the others here.

Well, here are three reasons for allowing it:

(1) It will make your job as programmer easier.

(2) It will be useful for people to take one of your units, convert it to
a float (or extract the scalar part), pass that to some other module's
function, then convert the answer back to the appropriate unit.

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



-- 
Steven.




More information about the Python-list mailing list