import textwrap
import inspect


def _get_source_str(func):
  """Returns a string representing the code of `func`.  Doesn't fail."""
  try:
    # The astute reader may note that this will get everything on the source
    # lines where the function was defined, including tokens outside the actual
    # function definition (e.g., for a lambda expression).  Unfortunately,
    # Python does not maintain character-level source information, so getting
    # this precisely right is nontrivial:
    # http://xion.io/post/code/python-get-lambda-code.html
    return textwrap.dedent(inspect.getsource(func)).rstrip()
  except (IOError, TypeError):
    # IOError happens if inspect.getsource can't find the source file.
    # TypeError happens if it's a callable that is not a module, class, method,
    # function, traceback, frame, or code object (e.g., functools.partial)
    return str(func).strip()