Python Function Inspection

      No Comments on Python Function Inspection

Consider the following code:

from __future__ import print_function

import inspect

def foo1(): pass
def foo2(arg1, arg2): pass
def foo3(arg1, arg2, arg3='def'): pass
def foo4(arg1, arg2='def', *args): pass
def foo5(arg1, arg2='def', **kwargs): pass
def foo6(arg1, arg2='def', *args, **kwargs): pass
def foo7(arg1, arg2, *args, **kwargs): pass
def foo8(arg1, arg2='def1', arg3='def2'): pass

functions = {f:v for f,v in locals().items() if f.startswith('foo')}
for name in sorted(functions.keys()):
    print(name, inspect.getargspec(functions[name]))

It produces the following output:

foo1 ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
foo2 ArgSpec(args=['arg1', 'arg2'], varargs=None, keywords=None, defaults=None)
foo3 ArgSpec(args=['arg1', 'arg2', 'arg3'], varargs=None, keywords=None, defaults=('def',))
foo4 ArgSpec(args=['arg1', 'arg2'], varargs='args', keywords=None, defaults=('def',))
foo5 ArgSpec(args=['arg1', 'arg2'], varargs=None, keywords='kwargs', defaults=('def',))
foo6 ArgSpec(args=['arg1', 'arg2'], varargs='args', keywords='kwargs', defaults=('def',))
foo7 ArgSpec(args=['arg1', 'arg2'], varargs='args', keywords='kwargs', defaults=None)
foo8 ArgSpec(args=['arg1', 'arg2', 'arg3'], varargs=None, keywords=None, defaults=('def1', 'def2'))

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.