import ast


def safe_eval_maths(expr):
    """
    Safely evaluates a maths expression,
    such as (2**32-1) or (400|0x1000)
    Will throw a ValueError exception on error

    Note: This is still susceptible to memory or CPU exhaustion by putting
          in large numbers.
    """
    allowed = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.operator,
               ast.unaryop, ast.Num)
    try:
        tree = ast.parse(expr, mode='eval')
        valid = all(isinstance(n, allowed) for n in ast.walk(tree))
        if valid:
            return eval(expr, {"__builtins__": None})
    except Exception as e:
        raise ValueError("Refusing to execute " + expr + str(e))