如何在Python中找出方法的多样性 [英] How to find out the arity of a method in Python

查看:72
本文介绍了如何在Python中找出方法的多样性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找出Python中某个方法的实用性(它接收的参数数量). 现在我正在这样做:

def arity(obj, method):
  return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self

class Foo:
  def bar(self, bla):
    pass

arity(Foo(), "bar")   # => 1

我希望能够实现这一目标:

Foo().bar.arity()   # => 1

更新:现在,上述函数无法使用内置类型,对此的任何帮助也将不胜感激:

 # Traceback (most recent call last):
 #   File "bla.py", line 10, in <module>
 #     print arity('foo', 'split')  # =>
 #   File "bla.py", line 3, in arity
 #     return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
 # AttributeError: 'method_descriptor' object has no attribute 'func_co

Python的标准库中的

解决方案

模块inspect是您的朋友-请参见varargs和/或varkw而不是None,则arity可以是从无穷大到无穷大的任何值,如果defaults不是None,则某些参数可以省略(默认).你怎么把它变成一个数字,打败了我,但是想必你有主意了!-)

这适用于Python编码的函数,但不适用于C编码的函数.除了通过C编码的函数(包括内置函数)的文档字符串(或可选地通过Python 3中的注释)外,Python C API中的任何内容都不允许C编码的函数(包括内置函数)公开其内省的签名;因此,如果其他方法失败(当然,文档字符串也可能会丢失,在这种情况下,该功能将仍然是个谜),您将需要作为最后的切入点来解析文档字符串. >

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):
  return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self

class Foo:
  def bar(self, bla):
    pass

arity(Foo(), "bar")   # => 1

I'd like to be able to achieve this:

Foo().bar.arity()   # => 1

Update: Right now the above function fails with built-in types, any help on this would also be appreciated:

 # Traceback (most recent call last):
 #   File "bla.py", line 10, in <module>
 #     print arity('foo', 'split')  # =>
 #   File "bla.py", line 3, in arity
 #     return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
 # AttributeError: 'method_descriptor' object has no attribute 'func_co

解决方案

Module inspect from Python's standard library is your friend -- see the online docs! inspect.getargspec(func) returns a tuple with four items, args, varargs, varkw, defaults: len(args) is the "primary arity", but arity can be anything from that to infinity if you have varargs and/or varkw not None, and some arguments may be omitted (and defaulted) if defaults is not None. How you turn that into a single number, beats me, but presumably you have your ideas in the matter!-)

This applies to Python-coded functions, but not to C-coded ones. Nothing in the Python C API lets C-coded functions (including built-ins) expose their signature for introspection, except via their docstring (or optionally via annotations in Python 3); so, you will need to fall back to docstring parsing as a last ditch if other approaches fail (of course, the docstring might be missing too, in which case the function will remain a mystery).

这篇关于如何在Python中找出方法的多样性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆