def plural_to_python(expr):
    """Gets a C expression as used in PO files for plural forms and returns a
    Python function that implements an equivalent expression.

    >>> f = plural_to_python('(n != 1)')
    >>> f(0), f(1), f(2), f(3)
    (1, 0, 1, 1)

    >>> f = plural_to_python('n==1 ? 0 : n==2 ? 1 : 2')
    >>> f(0), f(1), f(2), f(3)
    (2, 0, 1, 2)

    >>> f = plural_to_python('(n==1')
    Traceback (most recent call last):
      ...
    ValueError: Syntax error in plural form expression

    >>> f = plural_to_python('(foo==1)')
    Traceback (most recent call last):
      ...
    ValueError: Unsafe plural form expression

    :param expr: a string containing a C expression as used for plural forms
                 in PO files
    :return: the Python equivalent of the expression as a callable that expects
             the number as single positional argument
    :rtype: ``callable``
    
    :note: The implementation of this function is based on the ``c2py``
           function in the standard ``gettext`` module.
    """
    # Security check, allow only the "n" identifier
    tokens = tokenize.generate_tokens(StringIO(expr).readline)
    try:
        if [x for x in tokens if x[0] == token.NAME and x[1] != 'n']:
            raise ValueError('Unsafe plural form expression')
    except tokenize.TokenError:
        raise ValueError('Syntax error in plural form expression')

    # Replace some C operators by their Python equivalents
    expr = expr.replace('&&', ' and ').replace('||', ' or ')
    expr = re.sub(r'\!([^=])', ' not \\1', expr)

    # Define C-like "cond ? true : false"
    def _test(condition, true, false):
        if condition:
            return true
        else:
            return false

    # Regular expression and replacement function used to transform
    # "a?b:c" to "test(a,b,c)".
    regex = re.compile(r'(.*?)\?(.*?):(.*)')
    def _repl(m):
        return "test(%s, %s, %s)" % (m.group(1), m.group(2),
                                     regex.sub(_repl, m.group(3)))

    # Code to transform the plural expression, taking care of parentheses
    stack = ['']
    for char in expr:
        if char == '(':
            stack.append('')
        elif char == ')':
            subexpr = regex.sub(_repl, stack.pop())
            stack[-1] += '(%s)' % subexpr
        else:
            stack[-1] += char
    expr = regex.sub(_repl, stack.pop())

    try:
        return eval('lambda n: int(%s)' % expr, {'test': _test}, {})
    except SyntaxError:
        raise ValueError('Syntax error in plural form expression')


