Suppose you have the following scenario:
You have a dammmmmmmn long argument list for the function foo:
def foo( A='a', B='b', C='c', ... , Z='z' ) : url = 'A=%s&' % (A) + 'B=%s&' % (B) + ... + 'Z=%s&' % (Z)
How to make it more user/developer friendly?
foo( F='ft', B='bs')
For the foo function developer, it is still tedious to repeat the boring expressions. Remember, python is an elegant language. Let’s abstract this problem: is there anyway to access the (name, value) pair of function arguments directly? As you know, python is a pure object-oriented programming language, everything is object, so it is with function. There might be some interface exposed for this purpose.
Not really, the function object does expose several attributes, like func_defaults, which stores the (name, value) pair for default values, and func_name, that records the name of the function itself, but there is no “argument dictionary”at all. Google, and here is a post discussing inspect module, which is mainly used in debugging. Here is the example to implement the same functionality with more pythonic style:
import inspect def foo( A='a', B='b', C='c', ... , Z='z' ) : argv = inspect.getargvalues( inspect.currentframe() )[-1].items(); url = '%'.join( [ '%s=%s' % (k,v) for k,v in argv.items() ] )
NOTE: Ln4 should be called before any local variables declared, otherwise, argv would include the declared local variables before Ln4.
This trick is used in user interface (e.g pyaws.ecs.ItemLookup)
UPDATE: A better approach is to use the built-in function vars.