emcek
emcek

Reputation: 535

How to make general type checker in python

I got some similar code to this. Not exacly, but I don't to put to much, but I need that check_type accept r_type parameter as string and check if object type is of value of this string. It is doable?!?!?

I repeat can't do that: n.check_type(r_type=Newer)*, I need take r_type value from configuration file and thats way is a string!

    class New(object):
        def check_type(self, r_type):
            print 'is instance of r_type: ', isinstance(self, r_type)
            return isinstance(self, r_type)

    class Newer(New):
        pass

    if __name__ == '__main__':
        n = Newer()
        n.check_type(r_type='Newer')

Output:

        print 'is instance of r_type: ', isinstance(self, r_type)
    TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

Upvotes: 0

Views: 59

Answers (2)

Copperfield
Copperfield

Reputation: 8510

you can use the global dictionary to get the actual class by its name and use it to check with isinstance

>>> class New(object):
        def check_type(self,r_type):
            result = isinstance(self,globals()[r_type])
            print "is instance of r_type: ",result
            return result


>>> class Newer(New):
        pass

>>> n=Newer()
>>> n.check_type("Newer")
is instance of r_type:  True
True
>>> 

Upvotes: 3

GreenAsJade
GreenAsJade

Reputation: 14685

Instead of trying to call isInstance, you could just compare the names of the types directly:

class New(object):
    def check_type(self, r_type):
        return str(type(self)) == r_type

class Newer(New):
    pass

if __name__ == '__main__':
    n = Newer()
    print n.check_type(r_type="<class '__main__.Newer'>")

Obviously, you might want to munge the type name to extract just the basename of the type and compare that, for ease of specifying :)

Upvotes: 0

Related Questions