[Python-3000] __contains__ automatic coercion / unit conversion lib

Tomasz Melcer liori at exroot.org
Thu Jul 3 23:33:16 CEST 2008


Python 2.x automatically converts the return value of __contains__ into
bool. There was a thread here about changing this in py3k
but I cannot find whether this change has been accepted. It isn't in
recent tarball. If it was, this could be used f.e. to make a unit
conversion library with a natural API:

>>> from units import *
>>> radius_of_earth = Kilometers(6600)
>>> radius_of_earth in Meters
6600000 Meters

I guess it is a bit late for making this change now. I don't know python
source code well enough to make a patch, but I hope maybe this will
motivate someone to do so. Here's example code:

class Unit(object):
    class __metaclass__(type):
       def __contains__(dest_unit, value):
          if isinstance(value, Unit):
             return dest_unit(unit_convert(value.__class__,Unit,value))
             return Unit(value)

    def __init__(self, value):
       self.value = value

    def __repr__(self):
       return "%d %s" % (self.value, self.__class__.__name__)

class Meters(Unit): pass
class Kilometers(Unit): pass
class Centimeters(Unit): pass

# read as "Kilometer is 1000 Meters"
conv = [
    [Kilometers, 1000.0, Meters],
    [Meters, 100.0, Centimeters]

class CannotConvert(Exception): pass

def unit_convert(funit, tunit, value):
    for f, m, t in conv:
        if (funit is f) and (tunit is t):
            return m*value
        elif (funit is t) and (tunit is f):
            return value/m
    raise CannotConvert

Tomasz Melcer

More information about the Python-3000 mailing list