title: Is there a built-in or more Pythonic way to try to parse a string to an integer
body: <p>I had to write the following function to fail gracefully when trying to parse a string to an integer. I would imagine Python has something built in to do this, but I can't find it. If not, is there a more Pythonic way of doing this that doesn't require a separate function?</p>
  
  <pre><code>def try_parse_int(s, base=10, val=None):
    try:
      return int(s, base)
    except ValueError:
      return val
  </code></pre>
  
  <p>The solution I ended up using was a modification of @sharjeel's answer. The following is functionally identical, but, I think, more readable.</p>
  
  <pre><code>def ignore_exception(exception=Exception, default_val=None):
    """Returns a decorator that ignores an exception raised by the function it
    decorates.
  
    Using it as a decorator:
  
      @ignore_exception(ValueError)
      def my_function():
        pass
  
    Using it as a function wrapper:
  
      int_try_parse = ignore_exception(ValueError)(int)
    """
    def decorator(function):
      def wrapper(*args, **kwargs):
        try:
          return function(*args, **kwargs)
        except exception:
          return default_val
      return wrapper
    return decorator
  </code></pre>