def ensure_fd(fd):
    """Ensure an argument is a file descriptor."""
    if not isinstance(fd, int):
        if not hasattr(fd, 'fileno'):
            raise TypeError(
                'Arguments must be file descriptors, or implement fileno()')
        return fd.fileno()
    return fd
