conversion of volume units available units cubic metre litre kilolitre gallon cubic yard cubic foot cup usage import this file into their respective project use the function lengthconversion for conversion of volume units parameters value the number of from units you want to convert fromtype from which type you want to convert totype to which type you want to convert references wikipedia reference https en wikipedia orgwikicubicmetre wikipedia reference https en wikipedia orgwikilitre wikipedia reference https en wiktionary orgwikikilolitre wikipedia reference https en wikipedia orgwikigallon wikipedia reference https en wikipedia orgwikicubicyard wikipedia reference https en wikipedia orgwikicubicfoot wikipedia reference https en wikipedia orgwikicupunit conversion between volume units volumeconversion4 cubic meter litre 4000 volumeconversion1 litre gallon 0 264172 volumeconversion1 kilolitre cubic meter 1 volumeconversion3 gallon cubic yard 0 017814279 volumeconversion2 cubic yard litre 1529 1 volumeconversion4 cubic foot cup 473 396 volumeconversion1 cup kilolitre 0 000236588 volumeconversion4 wrongunit litre traceback most recent call last valueerror invalid fromtype value wrongunit supported values are cubic meter litre kilolitre gallon cubic yard cubic foot cup conversion between volume units volume_conversion 4 cubic meter litre 4000 volume_conversion 1 litre gallon 0 264172 volume_conversion 1 kilolitre cubic meter 1 volume_conversion 3 gallon cubic yard 0 017814279 volume_conversion 2 cubic yard litre 1529 1 volume_conversion 4 cubic foot cup 473 396 volume_conversion 1 cup kilolitre 0 000236588 volume_conversion 4 wrongunit litre traceback most recent call last valueerror invalid from_type value wrongunit supported values are cubic meter litre kilolitre gallon cubic yard cubic foot cup
from typing import NamedTuple


class FromTo(NamedTuple):
    from_factor: float
    to_factor: float


METRIC_CONVERSION = {
    "cubic meter": FromTo(1, 1),
    "litre": FromTo(0.001, 1000),
    "kilolitre": FromTo(1, 1),
    "gallon": FromTo(0.00454, 264.172),
    "cubic yard": FromTo(0.76455, 1.30795),
    "cubic foot": FromTo(0.028, 35.3147),
    "cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
    
    if from_type not in METRIC_CONVERSION:
        raise ValueError(
            f"Invalid 'from_type' value: {from_type!r}  Supported values are:\n"
            + ", ".join(METRIC_CONVERSION)
        )
    if to_type not in METRIC_CONVERSION:
        raise ValueError(
            f"Invalid 'to_type' value: {to_type!r}.  Supported values are:\n"
            + ", ".join(METRIC_CONVERSION)
        )
    return (
        value
        * METRIC_CONVERSION[from_type].from_factor
        * METRIC_CONVERSION[to_type].to_factor
    )


if __name__ == "__main__":
    import doctest

    doctest.testmod()