def _try_get_state_scope(name, mark_name_scope_used=True):
  """Returns a fresh variable/name scope for a module's state.

  In order to import a module into a given scope without major complications
  we require the scope to be empty. This function deals with deciding an unused
  scope where to define the module state. This is non trivial in cases where
  name_scope and variable_scopes are out of sync, e.g. tpus or re-entering
  scopes.

  Args:
    name: A string with the name of the module as supplied by the client.
    mark_name_scope_used: a boolean, indicating whether to mark the name
        scope of the returned value as used.

  Raises:
    RuntimeError: if the name scope of the freshly created variable scope is
        already used.
  """
  tmp_scope_name = tf_v1.get_variable_scope().name
  if tmp_scope_name:
    tmp_scope_name += "/"
  with tf.name_scope(tmp_scope_name):
    # Pick an unused variable scope.
    with tf_v1.variable_scope(
        None, default_name=name, auxiliary_name_scope=False) as vs:
      abs_state_scope = vs.name + "/"
    # Verify that the name scope is available and mark it used if requested.
    graph = tf_v1.get_default_graph()
    unique_name_scope = graph.unique_name(name, mark_name_scope_used) + "/"
    if unique_name_scope != abs_state_scope:
      raise RuntimeError(
          "variable_scope %s was unused but the corresponding "
          "name_scope was already taken." % abs_state_scope)
  return abs_state_scope