简体   繁体   English

获取 function python 中 arguments 的数量

[英]Get the number of arguments in a function python

I want to verify if the client gave the right amount of arguments to the server.我想验证客户端是否向服务器提供了适量的 arguments。

I have this function:我有这个 function:

def invite_player(addr, active_users):

how can I verify the number of arguments of this function?如何验证此 function 的 arguments 的数量?

You can get the argument count of a function and then compare it.您可以获取 function 的参数计数,然后进行比较。

I assume that your function don't takes any keyword argument.我假设您的 function 不接受任何关键字参数。

>>> def invite_player(addr, active_users):
    ...


>>> invite_player.__code__.co_argcount
2

The better way would be using builtin inspect module:更好的方法是使用内置检查模块:

>>> import inspect
>>> def invite_player(addr, active_users):
    ...


>>> inspect.getfullargspec(invite_player)
FullArgSpec(args=['addr', 'active_users'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})
>>> inspect.getfullargspec(invite_player)[0]
['addr', 'active_users']
>>> len(inspect.getfullargspec(invite_player)[0])
2

Also a TypeError would raise if you don't pass right amount of arguments to the function, but this is not the only thing that raises TypeError .如果您没有将适量的 arguments 传递给 function,也会引发TypeError ,但这并不是引发TypeError的唯一原因。

As mentioned in the comments, the function can only be called with 2 arguments.正如评论中提到的,function 只能用 2 个 arguments 调用。 If not, a TypeError will be raised.如果不是,则会引发 TypeError。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM