How to find out the arity of a method in Python

后端 未结 5 1604
滥情空心
滥情空心 2020-11-30 03:48

I\'d like to find out the arity of a method in Python (the number of parameters that it receives). Right now I\'m doing this:

def arity(obj, method):
  retur         


        
5条回答
  •  天命终不由人
    2020-11-30 04:32

    here is another attempt using metaclass, as i use python 2.5, but with 2.6 you could easily decorate the class

    metaclass can also be defined at module level, so it works for all classes

    from types import FunctionType
    
    def arity(unboundmethod):
        def _arity():
            return unboundmethod.func_code.co_argcount - 1 # remove self
        unboundmethod.arity = _arity
    
        return unboundmethod
    
    class AirtyMetaclass(type):
        def __new__(meta, name, bases, attrs):
            newAttrs = {}
            for attributeName, attribute in attrs.items():
                if type(attribute) == FunctionType:
                    attribute = arity(attribute)
    
                newAttrs[attributeName] = attribute
    
            klass = type.__new__(meta, name, bases, newAttrs)
    
            return klass
    
    class Foo:
        __metaclass__ = AirtyMetaclass
        def bar(self, bla):
            pass
    
    print Foo().bar.arity()
    

提交回复
热议问题