tags:

views:

92

answers:

4

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

myfunc.func_code.co_argcount

But built-in functions don't have the func_code 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.

+1  A: 

I don't believe this type of introspection is possible with built-in functions, or any C extension function for that matter.

A similar question was already asked here, and Alex's answer suggests parsing the docstring of the function to determine the number of args.

flashk
A: 

It's not possible. C functions do not expose their argument signatures programmatically.

Alex Gaynor
+2  A: 

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')

   print
ars
A: 

Interesting solution, ars. Hope it helps others too.

I went another way: I had heared that Pypy is python implemented mostly in itself. So I tried PyPy (JIT version) and it worked. I haven't found a "hard-coded" function yet. Couldn't find out how to install it in /usr, but it works from a folder where it's unpacked.

culebrón