import re


def rpm_version(version, use_macro=True):
    """Converts a Python version into rpm equivalent or the named variable.

    Python versions may contain a suffix indicating that it is a pre-
    release or post-release version.  RPM implements pre-relase
    versions with a tilde separator, and post-release versions with a
    caret separator.

    If use_macro is True, then the string "%{pypi_version}" will be
    returned when there is no pre or post-release suffix.
    """
    if use_macro:
        default = '%{pypi_version}'
    else:
        default = version
    re_match = re.compile(
        r"(\d+\.?\d*\.?\d*\.?\d*)\.?((?:a|b|rc|post|dev)\d*)").search(
            version)
    if not re_match:
        return default
    rpm_version, rpm_suffix = re_match.groups()
    if rpm_suffix.startswith("post"):
        return '{}^{}'.format(rpm_version, rpm_suffix)
    if rpm_suffix.startswith("dev"):
        return '{}~~{}'.format(rpm_version, rpm_suffix)
    else:
        return '{}~{}'.format(rpm_version, rpm_suffix)