Beispiel #1
0
    def __findUnit(self):
        """
        Take a string like kV and work out prefix and units, obviously
        there is scope for collision between units and prefixes...

        :return: :mod:`Unit` object
        """
        if not self.unit:
            return NO_UNIT

        if isinstance(self.unit, Unit.Unit):
            return self.unit

        u = self.unit
        if Unit.hasUnit(u):
            return Unit.getUnit(u)

        # Work backwards through the list trying to find a unit that matches
        unit = self.unit = None
        ul = list(u)
        u = ""

        while ul:
            u = (ul.pop() + u)
            if Unit.hasUnit(u):
                unit = Unit.getUnit(u)
                break

        # Nothing left to look at
        if not ul:
            if not unit:
                # Make a temporary unit, since we don't know what this is
                unit = Unit.Unit(u, u, True)
            return unit

        # We have left overs... this should be a prefix...
        ul = ''.join(ul)
        if Prefix.hasPrefix(ul):
            self.amount *= Prefix.getPrefix(ul)
        return unit
Beispiel #2
0
    def to(self, prefix):
        u"""
        Convert to different prefix (i.e. seconds to ms) with no units e.g.

        >>> q = Quantity(1, 'km')
        >>> q
        1.0 km
        >>> q.to('m')
        1000.0
        >>> q.to('mm')
        1000000.0
        >>> q.to('Mm')
        0.001

        :param prefix: A prefix / unit to convert to
        :return: A floating point scalar or None for invalid prefix
        """
        if prefix.endswith(self.unit.unit):
            prefix = prefix[:-len(self.unit.unit)]

        if Prefix.hasPrefix(prefix):
            return int(self) / Prefix.getPrefix(prefix)

        return None