Determining the number of parameters in a lambda

前端 未结 3 1957
你的背包
你的背包 2021-01-31 02:43

I am wondering if there is a way to determine (given a variable containing a lambda) the number of parameters the lambda it contains. The reason being, I wish to call a functio

3条回答
  •  一个人的身影
    2021-01-31 03:14

    From the documentation on callable types, the func_code attribute of functions contains a code object, and from the inspect module documentation on code objects there is a co_argcount member that contains the number of arguments (not including * or ** args).

    So the best way to get this information from a lambda function (or any function) is to use func.func_code.co_argcount:

    >>> foo = lambda a, b, *args, **kwargs: None
    >>> foo.func_code.co_argcount
    2
    

提交回复
热议问题