import pywikibot
import time

def get_ids_of_parent_class(q_item):
    parents = []
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    wd_item_subclass = pywikibot.ItemPage(repo, q_item)
    item_dict = wd_item_subclass.get()
    clm_dict = item_dict["claims"]
    if "P279" in clm_dict:
        for x in clm_dict["P279"]:
            clm_trgt = x.getTarget()
            parents.append(clm_trgt.getID())
    return parents


def is_subclass_of(q_child, q_parent, path=[]):
    if q_child == q_parent:
        return True
    else:
        parents = get_ids_of_parent_class(q_child)
        for parent_class in parents:
            if parent_class not in path:
                path.append(parent_class)
                return is_subclass_of(parent_class, q_parent, path)
    return False


def is_human_settlement(q_item):
    result = False
    settlement_q = "Q486972"
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    wd_item = pywikibot.ItemPage(repo, q_item)
    item_dict = wd_item.get()
    clm_dict = item_dict["claims"]
    if "P31" in clm_dict:
        for x in clm_dict["P31"]:
            clm_trgt = x.getTarget()
            id_to_test = clm_trgt.getID()
            subclass_test = is_subclass_of(id_to_test, settlement_q)
            print(id_to_test, settlement_q)
            print("subclass test - ", subclass_test)
            if subclass_test is True:
                result = True
    return result


#print(is_human_settlement("Q28374"))
#print(is_human_settlement("Q25411"))
print("****")
print(is_subclass_of("Q12813115", "Q486972", []))
print("---")
print(is_subclass_of("Q146", "Q19088", []))
print(is_subclass_of("Q146", "Q19088", []))
print("...")
print(is_subclass_of("Q12813115", "Q486972", []))
****
True
---
True
True
...
True