Finding Function Args?

Graham Dumpleton grahamd at dscpl.com.au
Tue Jun 15 03:05:41 EDT 2004


"Mike C. Fletcher" <mcfletch at rogers.com> wrote in message news:<mailman.960.1087267217.6949.python-list at python.org>...
> Check the standard module inspect, particularly;
> 
>  >>> import inspect
>  >>> import cgi
>  >>> inspect.getargspec( cgi.escape )
> (['s', 'quote'], None, None, (None,))

Also:

  cgi.escape.func_code.co_argcount

Should yield:

  2

Lots of func stuff should be visible when dir() is used. You just
need to work out what is where.

>>> dir(cgi.escape)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute__', '__hash__', '__init__', '__module__',
'__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__', 'func_closure', 'func_code',
'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

>>> dir(cgi.escape.func_code)
['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__str__', 'co_argcount', 'co_cellvars',
'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags',
'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals',
'co_stacksize', 'co_varnames']

Similar thing for class methods and callable objects if you know where
to look.

>>> dir(A.__init__.im_func)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute__', '__hash__', '__init__', '__module__',
'__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__', 'func_closure', 'func_code',
'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

>>> dir(A(1).__call__.im_func)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute__', '__hash__', '__init__', '__module__',
'__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__', 'func_closure', 'func_code',
'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

Obviously, the "inspect" module is mean't to hide to a degree all this
stuff, but still sometimes easier to access it directly.



More information about the Python-list mailing list