Home > Enterprise >  Check class instance passed to another module is of type class
Check class instance passed to another module is of type class

Time:07-31

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?

CodePudding user response:

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'}

CodePudding user response:

Yes, python needs to know which class you are checking because you can have two different classes with the same name in different files.

In file sub.py you have to write:

from main import MyClass

def fun(i):
    if isinstance(i, MyClass): 
        return i.__dict__

But in case you importing fun into main.py you will get circular import, be careful)

CodePudding user response:

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

def fun(i):
    if isinstance(i, class): # <---- class is keyword in Python, you cannot use it 
                             #       like this. You can use as type(class)
        return i.__dict__
  • Related