import six
import socket


def get_message(queue, timeout=None):
  """Returns next message from queue.

  Args:
      queue (Queue): to retrieve next message from
      timeout (float): time to wait in seconds for incoming message to arrive.

  Raises:
      ValueError: if queue provided is not a valid queue object

  Returns:
      object: The message data or None if no messages were available or
              retrieved within timeout specified.
  """
  if queue is None or not hasattr(queue, "get") or not hasattr(
      queue, "task_done"):
    raise ValueError("Invalid queue of {} provided".format(type(queue)))

  message = None
  try:
    message = queue.get(block=True, timeout=timeout)
    queue.task_done()
    # manager shutdown or queue empty
  except (IOError, six.moves.queue.Empty, ValueError, socket.error):
    pass
  return message