def KeyHasAncestor(key, ancestor):
  """Return whether `ancestor` is an ancestor of key.

  An ancestor is defined as a key whose chain of (kind, value) pairs appears as
  a distinct prefix to another key's (kind, value) chain. For example:

    Key('Foo', 'id1') is an ancestor of Key('Foo', 'id1', 'Bar', 'id2')
    However, Key('Foo', 'id1') is not an ancestor of Key('Foo', 'id1')

  Args:
    key: ndb.Key, The key whose ancestry is being tested.
    ancestor: ndb.Key, The key being tested for the ancestor of `key`.

  Returns:
    bool, Whether `ancestor` is an ancestor of `key`.
  """
  key_ancestor = key.parent()
  while key_ancestor:
    if key_ancestor == ancestor:
      return True
    key_ancestor = key_ancestor.parent()
  return False