Wednesday, October 31, 2012

Python: validate if attribute is a instance method


Use type() or isinstance() functions:

# test.py

import types

class Person():
    def __init__(self,fistname,lastname):
        self.fistname = fistname
        self.lastname = lastname
        
    def run(self):
        print "run"
        
    def jump(self):
        print "jump"

myPerson = Person("jack","smith")
for name in dir(myPerson):
    print "name: %s" % (name)
    myAttrib = getattr(myPerson, name)
    print "myAttrib: %s" % (myAttrib)    
    print "(type(myAttrib)) == types.MethodType: %s" % ((type(myAttrib)) == types.MethodType)
    print "isinstance(myAttrib, types.MethodType: %s" % (isinstance(myAttrib, types.MethodType))
   
Result:


C:\Users\John\Desktop>python test.py
name: __doc__
myAttrib: None
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: __init__
myAttrib: <bound method Person.__init__ of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: __module__
myAttrib: __main__
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: fistname
myAttrib: jack
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: jump
myAttrib: <bound method Person.jump of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: lastname
myAttrib: smith
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: run
myAttrib: <bound method Person.run of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True

Resources:
http://stackoverflow.com/questions/624926/how-to-detect-whether-a-python-variable-is-a-function
http://docs.python.org/2/library/types.html
http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python


No comments: