Why do people say isinstance is bad?

If I have my own class, named Test, and if I want to check an variable to see if it is an instance of Test or Test's child classes, is using instance() bad?

Recommended Answers

All 10 Replies

They say its bad? Crap. :/

It's bad because it isn't friendly to other objects that act like your class.

You should use hasattr instead to check that the object you are working with is appropriate. That way as long as the object has the required attribute or method it will work with your code as well as your own objects. (If it is a method it still must accept the appropriate arguments.)

class YourClass:

    def required_method(self):
        pass

class MyClass:

    def required_method(self):
        pass

yourobj = YourClass()
myobj = MyClass()

isinstance(yourobj, YourClass)    #True
isinstance(myobj, YourClass)    #False
hasattr(yourobj, 'required_method')    #True
hasattr(myobj, 'required_method')    #True

well other classes that acts like my class should be inherited.

Talking about inheritance, isinstance() might be somewhat confusing to beginners when it comes to an inherited class ...

class Class1:
    def method1(self):
        pass
    
class Class2(Class1):
    def method1(self):
        pass

c1 = Class1()
c2 = Class2()

print( isinstance(c1, Class1) )  # True
print( isinstance(c1, Class2) )  # False
print( isinstance(c2, Class1) )  # True --> Class1 is inherited
print( isinstance(c2, Class2) )  # True

Yeah that's exactly what I want, to check if an instance is a class or its child class.

And for what purpose you need that information?

make sure that a function is receiving the proper type.

If I have another object that's different from the type i want and have the same method name but does different things, it might screw up the process of the API.

Can you give concrete example of the API (You can have alternative input by having keyword parameters, inputstring='', inputlist=[], also you can use parameter "iterized": give parameter (inputstring,) or [inputstring] instead of inputstring)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.