def _add_sub(self, other, op):
        """Implements both addition and subtraction."""
        if not isinstance(other, Number):
            return NotImplemented

        # If either side is unitless, inherit the other side's units.  Skip all
        # the rest of the conversion math, too.
        if self.is_unitless or other.is_unitless:
            return Number(
                op(self.value, other.value),
                unit_numer=self.unit_numer or other.unit_numer,
                unit_denom=self.unit_denom or other.unit_denom,
            )

        # Likewise, if either side is zero, it can auto-cast to any units
        if self.value == 0:
            return Number(
                op(self.value, other.value),
                unit_numer=other.unit_numer,
                unit_denom=other.unit_denom,
            )
        elif other.value == 0:
            return Number(
                op(self.value, other.value),
                unit_numer=self.unit_numer,
                unit_denom=self.unit_denom,
            )

        # Reduce both operands to the same units
        left = self.to_base_units()
        right = other.to_base_units()

        if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom:
            raise ValueError("Can't reconcile units: %r and %r" % (self, other))

        new_amount = op(left.value, right.value)

        # Convert back to the left side's units
        if left.value != 0:
            new_amount = new_amount * self.value / left.value

        return Number(new_amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom)
def _add_sub ( self , other , op ) : if not isinstance ( other , Number ) : return NotImplemented if self . is_unitless or other . is_unitless : return Number ( op ( self . value , other . value ) , unit_numer = self . unit_numer or other . unit_numer , unit_denom = self . unit_denom or other . unit_denom , ) if self . value == 0 : return Number ( op ( self . value , other . value ) , unit_numer = other . unit_numer , unit_denom = other . unit_denom , ) elif other . value == 0 : return Number ( op ( self . value , other . value ) , unit_numer = self . unit_numer , unit_denom = self . unit_denom , ) left = self . to_base_units ( ) right = other . to_base_units ( ) if left . unit_numer != right . unit_numer or left . unit_denom != right . unit_denom : raise ValueError ( "Can't reconcile units: %r and %r" % ( self , other ) ) new_amount = op ( left . value , right . value ) if left . value != 0 : new_amount = new_amount * self . value / left . value return Number ( new_amount , unit_numer = self . unit_numer , unit_denom = self . unit_denom )
Implements both addition and subtraction.