Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Introspection for functions/methods using inspect modules
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import inspect
def func1(arg1, arg2, arg3):
pass
def func2(arg1, arg2, arg3='arg3_default'):
pass
def func3(arg1, arg2='arg2_default', arg3='arg3_default', *args, **kwargs):
pass
def describe_func(func):
print "Name:", func.func_name
print "Code:"
print inspect.getsource(func)
argspec = inspect.getargspec(func)
describe_args(argspec)
print "--"
print
def describe_args(argspec):
args_with_defaults = argspec.defaults or []
num_fixed_args = len(argspec.args)
num_fixed_args_with_defaults = len(args_with_defaults)
num_fixed_args_without_defaults = num_fixed_args - num_fixed_args_with_defaults
print "Named args (without defaults)", argspec.args[:num_fixed_args_without_defaults]
if argspec.defaults:
args_with_default = argspec.args[len(argspec.args)-len(argspec.defaults):]
print "Named args with default", args_with_default
for index,arg in enumerate(args_with_default):
print "\tArg name: %s, default = %s" % (arg, str(argspec.defaults[index]))
print "Varargs param:", argspec.varargs or 'Not defined'
print "keywords param:", argspec.keywords or 'Not defined'
class Class1(object):
def method1(self, arg1, arg2='value2'):
pass
describe_func(func1)
describe_func(func2)
describe_func(func3)
obj1 = Class1()
describe_func(obj1.method1)
Name: func1
Code:
def func1(arg1, arg2, arg3):
pass
Named args (without defaults) ['arg1', 'arg2', 'arg3']
Varargs param: Not defined
keywords param: Not defined
--
Name: func2
Code:
def func2(arg1, arg2, arg3='arg3_default'):
pass
Named args (without defaults) ['arg1', 'arg2']
Named args with default ['arg3']
Arg name: arg3, default = arg3_default
Varargs param: Not defined
keywords param: Not defined
--
Name: func3
Code:
def func3(arg1, arg2='arg2_default', arg3='arg3_default', *args, **kwargs):
pass
Named args (without defaults) ['arg1']
Named args with default ['arg2', 'arg3']
Arg name: arg2, default = arg2_default
Arg name: arg3, default = arg3_default
Varargs param: args
keywords param: kwargs
--
Name: method1
Code:
def method1(self, arg1, arg2='value2'):
pass
Named args (without defaults) ['self', 'arg1']
Named args with default ['arg2']
Arg name: arg2, default = value2
Varargs param: Not defined
keywords param: Not defined
--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment