def to_file_descriptor(fobj):
    """
    Converts an object to a file descriptor. The given object can be either:

     - An integer file descriptor
     - An object with a ``fileno()`` method.

    :raises ValueError: If the given object cannot be converted.

        >>> class Descriptable:
        ...     def fileno(self):
        ...         return 42
        ...
        >>> to_file_descriptor(Descriptable())
        42
        >>> to_file_descriptor(42)
        42
        >>> try:
        ...     to_file_descriptor(object())
        ... except ValueError:
        ...     print('Failure')
        ...
        Failure
    """
    if isinstance(fobj, int):
        return fobj
    elif hasattr(fobj, 'fileno'):
        return fobj.fileno()
    else:
        raise ValueError(
            '{} cannot be converted to a file descriptor'.format(fobj))