culebrón culebrón - 1 year ago 47
Python Question

How to get the number of args of a built-in function in Python?

I need to programmatically get the number of arguments that a function requires. With functions declared in modules this is trivial:


But built-in functions don't have the
attribute. Is there another way to do this? Otherwise I can't use the built-ins and have to re-write them in my code.

[addition] Thanks for the responses, hope they'll be useful. I have used Pypy instead.

ars ars
Answer Source

Take a look at the function below copied from here. This may be the best you can do. Note the comments about inspect.getargspec.

def describe_builtin(obj):
   """ Describe a builtin function """

   wi('+Built-in Function: %s' % obj.__name__)
   # Built-in functions cannot be inspected by
   # inspect.getargspec. We have to try and parse
   # the __doc__ attribute of the function.
   docstr = obj.__doc__
   args = ''

   if docstr:
      items = docstr.split('\n')
      if items:
         func_descr = items[0]
         s = func_descr.replace(obj.__name__,'')
         idx1 = s.find('(')
         idx2 = s.find(')',idx1)
         if idx1 != -1 and idx2 != -1 and (idx2>idx1+1):
            args = s[idx1+1:idx2]
            wi('\t-Method Arguments:', args)

   if args=='':
      wi('\t-Method Arguments: None')