Check if a function is a method of some object

后端 未结 3 417
广开言路
广开言路 2021-02-07 13:52

How to check if a function is a method of some object?

For example:

def check_method(f):
    ...

check_method(lambda x: x + 1)           # >>>          


        
相关标签:
3条回答
  • 2021-02-07 14:32

    A twist to the question involves asking to check if some function name would be available as a method. Since duck typing is considered pythonic there should be a simple

    hasmethod(obj, 'some_method')
    

    but it seems, there isn't.

    Duck typing seems to be best done by just trying:

    try:
      obj.some_method()
    except:
      # try something else
    

    If someone wants a function to check programmatically if an object has a method with a certain variable name, then the following function has been mentioned:

    def hasmethod(obj, method_name):
      return hasattr(obj, method_name) and callable(getattr(obj, method_name))
    

    But for Python 3 and 3.1 at least you need to get callable() back which was removed. A discussion of the want of bringing it back can be found in a python bug entry Resurrect callable with e.g.:

    def callable(obj):
        return isinstance(obj, collections.Callable) 
    

    This is straight from the above mentioned python bugtracker. Other sources on stackoverflow mention

    callable = lambda o: hasattr(o, '__call__') or isinstance(o, collections.Callable)
    

    which adds the hasattr to the call. Both work fine in my use case

    >>> bstr = b'spam'
    >>> str = 'eggs'
    >>> hasmethod(str, 'decode')
    False
    >>> hasmethod(bstr, 'decode')
    True
    

    For more details look at the already cited other question

    0 讨论(0)
  • 2021-02-07 14:36

    Use inspect.ismethod().

    The documentation states:

    Return true if the object is a bound method written in Python.

    This means that it will work as you intend for classes that you define in Python. However, for methods of built-in classes like list or classes implemented in extension modules it will return False.

    0 讨论(0)
  • 2021-02-07 14:37

    It is also possible to check against the types defined in the built in types library:

    import types
    isinstance(obj.method, types.MethodType) # True
    
    0 讨论(0)
提交回复
热议问题