Home > database >  Is there a way to check if a variable is an instance of an inner class whose outer class is a certai
Is there a way to check if a variable is an instance of an inner class whose outer class is a certai

Time:11-04

example code:

class A:
    class B:
        def __init__(self):
            pass

var = A.B()

i need a function, let's say check_if_class_parent(obj, class_type) that would check if var is an instance of an inner class whose outer class is A, which if i run check_if_class_parent(var, A), it would return True

sometimes the class structure could be like this:

class A:
    class B:
        def __init__(self):
            pass
        
        class C:
            def __init__(self):
                pass

var = A.B.C()
var_two = A.B()

check_if_class_parent(var, A), check_if_class_parent(var, B), and check_if_class_parent(var_two, A) would all return True, but check_if_class_parent(var, C) would return False

CodePudding user response:

  1. An outer attribute could be added to the inner classes, in which case it's just a matter of walking up any outer attributes found on a value's type to see if A can be reached. However this does add extra definitions.

  2. A search can be conducted starting from A. E.g. (and not accounting for any dastardly cyclic references at all):

def is_type_within(obj, type_):
    if isinstance(obj, type_):
        return True
    for attr in dir(type_):
        if attr.startswith('__'):
            continue
        if is_type_within(obj, getattr(type_, attr)):
            return True
    return False
  • Related