import click


def check(fn, error_message=None):
    """
    Creates callback function which raises click.BadParameter when `fn` returns `False` on given input.

    >>> @click.command()
    >>> @click.option('--probability', callback=check(lambda x: 0 <= x <= 1, "--probability must be between 0 and 1 (inclusive)"))
    >>> def f(probability):
    >>>     print('P:', probability)
    """
    def f(ctx, param, value):
        if fn(value):
            return value
        else:
            if error_message is None:
                msg = str(value)
            else:
                msg = '{}. Value: {}'.format(error_message, value)

            raise click.BadParameter(msg)

    return f