How to find out the arity of a method in Python

后端 未结 5 1607
滥情空心
滥情空心 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:17

    Ideally, you'd want to monkey-patch the arity function as a method on Python functors. Here's how:

    def arity(self, method):
        return getattr(self.__class__, method).func_code.co_argcount - 1
    
    functor = arity.__class__
    functor.arity = arity
    arity.__class__.arity = arity
    

    But, CPython implements functors in C, you can't actually modify them. This may work in PyPy, though.

    That's all assuming your arity() function is correct. What about variadic functions? Do you even want an answer then?

提交回复
热议问题