Dynamically pass a function arguments from a dict

Mark McEahern marklists at mceahern.com
Wed Feb 23 20:12:07 EST 2005


Dan Eloff wrote:

> How can you determine that func2 will only accept
> bar and zoo, but not foo and call the function with
> bar as an argument? 

Let Python answer the question for you:

 >>> def func2(bar='a', zoo='b'):
... pass
...
 >>> for name in dir(func2):
... print '%s: %s' % (name, getattr(func2, name))
...
__call__: <method-wrapper object at 0x008CAC30>
__class__: <type 'function'>
__delattr__: <method-wrapper object at 0x008CAC30>
__dict__: {}
__doc__: None
__get__: <method-wrapper object at 0x008CAC30>
__getattribute__: <method-wrapper object at 0x008CAC30>
__hash__: <method-wrapper object at 0x008CAC30>
__init__: <method-wrapper object at 0x008CAC30>
__module__: __main__
__name__: func2
__new__: <built-in method __new__ of type object at 0x1E0BAA50>
__reduce__: <built-in method __reduce__ of function object at 0x008CE5B0>
__reduce_ex__: <built-in method __reduce_ex__ of function object at 
0x008CE5B0>
__repr__: <method-wrapper object at 0x008CAC30>
__setattr__: <method-wrapper object at 0x008CAC30>
__str__: <method-wrapper object at 0x008CAC30>
func_closure: None
func_code: <code object func2 at 008D5020, file "<stdin>", line 1>
func_defaults: ('a', 'b')
func_dict: {}
func_doc: None
func_globals: {'func2': <function func2 at 0x008CE5B0>, 'name': 
'func_globals',
'__builtins__': <module '__builtin__' (built-in)>, '__name__': 
'__main__', 'foo
: <function foo at 0x008CE970>, '__doc__': None}
func_name: func2
 >>> for name in dir(func2.func_code):
... print '%s: %s' % (name, getattr(func2.func_code, name))
...
__class__: <type 'code'>
__cmp__: <method-wrapper object at 0x008CACF0>
__delattr__: <method-wrapper object at 0x008CACF0>
__doc__: code(argcount, nlocals, stacksize, flags, codestring, 
constants, names,

varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])

Create a code object. Not for the faint of heart.
__getattribute__: <method-wrapper object at 0x008CACF0>
__hash__: <method-wrapper object at 0x008CACF0>
__init__: <method-wrapper object at 0x008CACF0>
__new__: <built-in method __new__ of type object at 0x1E0B0C68>
__reduce__: <built-in method __reduce__ of code object at 0x008D5020>
__reduce_ex__: <built-in method __reduce_ex__ of code object at 0x008D5020>
__repr__: <method-wrapper object at 0x008CACF0>
__setattr__: <method-wrapper object at 0x008CACF0>
__str__: <method-wrapper object at 0x008CACF0>
co_argcount: 2
co_cellvars: ()
co_code: d S
co_consts: (None,)
co_filename: <stdin>
co_firstlineno: 1
co_flags: 67
co_freevars: ()
co_lnotab: ☺
co_name: func2
co_names: ()
co_nlocals: 2
co_stacksize: 1
co_varnames: ('bar', 'zoo')
 >>>

Hmm, func2.func_code.co_varnames seems to have the answer.

Cheers,

// m



More information about the Python-list mailing list