Search code examples
pythonclasstypesinstance

Check class instance passed to another module is of type class


How to check type of class instance object passed from another module. Does it require from main import MyClass? Or can I just generally check object is of type "(any) class instance"?

# main.py
#########

import sub

class MyClass():
    def __init__(self):
        self.z = 1

a = MyClass()
assert type(a) == MyClass
assert isinstance(a, MyClass) == True

b = sub.fun(a)



# sub.py
########

def fun(i):
    if isinstance(i, class):  # general instead of __main__.MyClass
        return i.__dict__

The above yields

NameError: name 'class' is not defined

Maybe it is not a good design and code shall be explicit rather than converting each class to dict?


Solution

  • I want to convert each class instance passed to fun to dictionary

    Try the below

    class Foo:
        def __init__(self, x):
            self.x = x
    
    
    class Bar:
        def __init__(self, x):
            self.x = x
    
    
    def fun(instance):
        if hasattr(instance, '__dict__'):
            return instance.__dict__
    
    
    print(fun(Foo(56)))
    print(fun(Bar("56")))
    

    output

    {'x': 56}
    {'x': '56'}