How to check whether a method exists in Python?

前端 未结 9 1195
栀梦
栀梦 2021-01-30 15:53

In the function __getattr__(), if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an objec

相关标签:
9条回答
  • 2021-01-30 16:03

    How about dir() function before getattr()?

    >>> "mymethod" in dir(dyn)
    True
    
    0 讨论(0)
  • 2021-01-30 16:04

    If your method is outside of a class and you don't want to run it and raise an exception if it doesn't exist:

    'mymethod' in globals()

    0 讨论(0)
  • 2021-01-30 16:06

    I use below utility function. It works on lambda, class methods as well as instance methods.

    Utility Method

    def has_method(o, name):
        return callable(getattr(o, name, None))
    

    Example Usage

    Let's define test class

    class MyTest:
      b = 'hello'
      f = lambda x: x
    
      @classmethod
      def fs():
        pass
      def fi(self):
        pass
    

    Now you can try,

    >>> a = MyTest()                                                    
    >>> has_method(a, 'b')                                         
    False                                                          
    >>> has_method(a, 'f')                                         
    True                                                           
    >>> has_method(a, 'fs')                                        
    True                                                           
    >>> has_method(a, 'fi')                                        
    True                                                           
    >>> has_method(a, 'not_exist')                                       
    False                                                          
    
    0 讨论(0)
  • 2021-01-30 16:07

    How about looking it up in dyn.__dict__?

    try:
        method = dyn.__dict__['mymethod']
    except KeyError:
        print "mymethod not in dyn"
    
    0 讨论(0)
  • 2021-01-30 16:10

    I think you should look at the inspect package. It allows you to 'wrap' some of the things. When you use the dir method it also list built in methods, inherited methods and all other attributes making collisions possible, e.g.:

    class One(object):
    
        def f_one(self):
            return 'class one'
    
    class Two(One):
    
        def f_two(self):
            return 'class two'
    
    if __name__ == '__main__':
        print dir(Two)
    

    The array you get from dir(Two) contains both f_one and f_two and a lot of built in stuff. With inspect you can do this:

    class One(object):
    
        def f_one(self):
            return 'class one'
    
    class Two(One):
    
        def f_two(self):
            return 'class two'
    
    if __name__ == '__main__':
        import inspect
    
        def testForFunc(func_name):
            ## Only list attributes that are methods
            for name, _ in inspect.getmembers(Two, inspect.ismethod):
                if name == func_name:
                    return True
            return False
    
        print testForFunc('f_two')
    

    This examples still list both methods in the two classes but if you want to limit the inspection to only function in a specific class it requires a bit more work, but it is absolutely possible.

    0 讨论(0)
  • 2021-01-30 16:14

    It's easier to ask forgiveness than to ask permission.

    Don't check to see if a method exists. Don't waste a single line of code on "checking"

    try:
        dyn.mymethod() # How to check whether this exists or not
        # Method exists and was used.  
    except AttributeError:
        # Method does not exist; What now?
    
    0 讨论(0)
提交回复
热议问题