#!/usr/bin/env python
# -*- coding: utf-8 -*-
import inspect
# tests
def test(foobar, mamibar='ola', tatibar='olee', *args, **kw):
pass
def test2(test, *taest, **mest):
pass
def test3(mami, tati, dedi, stric, teta='ok'):
pass
def test4(test='ok'):
pass
def test5(*arg):
pass
def test6():
pass
# function
def getattrs(func):
"""
Print function's original arguments (including defaults)
>>> getattrs(test)
Computed arguments: test(foobar, mamibar='ola', tatibar='olee', *args, **kw)
>>> getattrs(test2)
Computed arguments: test2(test, *taest, **mest)
>>> getattrs(test3)
Computed arguments: test3(mami, tati, dedi, stric, teta='ok')
>>> getattrs(test4)
Computed arguments: test4(test='ok')
>>> getattrs(test5)
Computed arguments: test5(*arg)
>>> getattrs(test6)
Computed arguments: test6()
"""
args = inspect.getargspec(func)
newargs = []
if args[3]:
razlika = len(args[0]) - len(args[3])
for i, arg in enumerate(args[0]):
if i < razlika:
newargs.append(arg)
else:
newargs.append('%s=\'%s\'' % (arg, args[3][i - razlika]))
if args[0] and not args[3]:
newargs.extend([arg for arg in args[0]])
if args[1]:
newargs.append('*' + args[1])
if args[2]:
newargs.append('**' + args[2])
if not newargs:
newargs = ['']
print "Computed arguments: %s(%s)" % (func.__name__, ', '.join(newargs))
if __name__ == '__main__':
import doctest
doctest.testmod()
Refactorings
No refactoring yet !
gsson
August 20, 2008, August 20, 2008 11:46, permalink
Something like this, perhaps?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import inspect
# tests
def test(foobar, mamibar='ola', tatibar='olee', *args, **kw):
pass
def test2(test, *taest, **mest):
pass
def test3(mami, tati, dedi, stric, teta='ok'):
pass
def test4(test='ok'):
pass
def test5(*arg):
pass
def test6():
pass
# function
def getattrs(func):
"""
Print function's original arguments (including defaults)
>>> getattrs(test)
Computed arguments: test(foobar, mamibar='ola', tatibar='olee', *args, **kw)
>>> getattrs(test2)
Computed arguments: test2(test, *taest, **mest)
>>> getattrs(test3)
Computed arguments: test3(mami, tati, dedi, stric, teta='ok')
>>> getattrs(test4)
Computed arguments: test4(test='ok')
>>> getattrs(test5)
Computed arguments: test5(*arg)
>>> getattrs(test6)
Computed arguments: test6()
"""
print "Computed arguments: %s%s" % (
func.__name__,
inspect.formatargspec(*inspect.getargspec(func)))
if __name__ == '__main__':
import doctest
doctest.testmod()
I bet there is some other, clever way to do this.