type-checking support in Python?

Aaron "Castironpi" Brady castironpi at gmail.com
Tue Oct 7 12:55:01 EDT 2008


On Oct 7, 5:24 am, Bas <wegw... at gmail.com> wrote:
> On Oct 7, 8:36 am, Lawrence D'Oliveiro <l... at geek-
>
> central.gen.new_zealand> wrote:
> > In message <mailman.2089.1223358567.3487.python-l... at python.org>, Gabriel
>
> > Genellina wrote:
> > > As an example, in the oil industry here in my country there is a mix of
> > > measurement units in common usage. Depth is measured in meters, but pump
> > > stroke in inches; loads in lbs but pressures in kg/cm².
>
> > Isn't the right way to handle that to attach dimensions to each number?
>
> What they taught me as a physics undergrad is to always convert random
> units given as input to SI units as soon as possible, do all your
> calculations internally in SI units and (only if really needed)
> convert back to arbitrary units on output.
(snip)

If you think it's a potential source of error, a lightweight version
wouldn't be hard to implement.  This one is absolute minimal, using
strings for the units.  Multiplication is harder, since you want 'foot
pounds' == 'pound feet'.

>>> class UnitScalar:
...     def __init__( self, val, type ):
...             self.val, self.type= val, type
...     def __add__( self, other ):
...             assert self.type== other.type, 'Must be same type'
...             return self.__class__( self.val+ other.val,
self.type )
...     def __repr__( self ):
...             return '<UnitScalar %f %s>'% ( self.val, self.type )
...
>>> a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'feet' )
>>> a+ b
<UnitScalar 5.000000 feet>
>>> a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'inches' )
>>> a+ b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __add__
AssertionError: Must be same type



More information about the Python-list mailing list