0

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´╝č

5
Contributors
10
Replies
11
Views
6 Years
Discussion Span
Last Post by pyTony
Featured Replies
  • 2

    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 … Read More

2

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
0

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
0

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.

0

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)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.