Extracting method parameter and default-values?

Alex Martelli aleaxit at yahoo.com
Wed Oct 4 06:15:08 EDT 2000


"Thomas Weholt" <thomas at cintra.no> wrote in message
news:8reo27$lmn$1 at oslo-nntp.eunet.no...
> Hi,
>
> I need to dig my way into an object, find its methods and extract the
> parameters to that method and their default values.

Python is quite good at such "introspection" tasks.


> A test-class:
> >>> class test:
>      def __init__(self):
>           self.a = ''
>      def met(self, b, c = [1,2,3], d = None):
>           self.a = 'thomas'
>           print self.a
> >>>x = test()
>
> I guess its somewhere here :
> >>> x.__class__.__dict__['met'].func_code

x.__class__.__dict__ will include all methods; they're the
entries with types.MethodType as their type().  So (after
an "import types", of course): [warning, untested]:

    def handle_an_object(x):
        for name, entry in x.__class__.__dict__:
            if type(entry)==types.MethodType:
                handle_the_method(name,entry)

> where x is my class and met is the name of the method. I need to get
> something like a dictionary with the parameters and their default values,

Since not all parameters have default values, you probably want
something like a pair (two-argument tuple): first, a sequence of
parameter names for parameters without default values; then, the
dictionary names->default for parameters WITH such a value.

entry.func_code.co_argcount gives you the overall count of
arguments (including self).
entry.func_code.co_varnames gives you the names of local
variables, starting with the arguments in order.

For default values, though, you must rather look at
entry.func_defaults: this is a tuple of the default
values for those arguments which have them (always the
latest, rightmost, ones, of course).


Alex






More information about the Python-list mailing list