简体   繁体   中英

Get function parameters as dictionary

I know that there are a lot of questions/answers on *arg, **kwarg. However, I'm doing something a little backwards and couldn't find it addressed (perhaps I just don't know how to ask the question.) Anyway, I want to simplify the below:

def foo(self, arg1, arg2, arg3):
     my_dict = dict(arg1=arg1, arg2=arg2, arg3=arg2)
     my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}".
               format(**my_dict)

note, I'd wrather not define foo as (self, **kwargs) as I like the autocomplete component of filling out the function.

Thanks,

The parameters are in the local namespace dict, so use it:

def foo(self, arg1, arg2, arg3):
     my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}".
               format(**locals())

inspect is what you are looking for:

import inspect

class T(object):
    def foo(self, arg1, arg2, arg3):
        frame = inspect.currentframe()
        args, _, _, values = inspect.getargvalues(frame)
        my_dict = {arg: values[arg] for arg in args if arg != 'self'}
        my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}".format(**my_dict)
        print my_dict
        print my_str

z = T()
z.foo(3,4,5)

note the arg != 'self' part as this is a method call. If you have a function with a parameter self this will not display that parameter.

As @dmg mentioned you can use inspect :

import inspect

def find_args(f):
    return inspect.getargspec(f)[0]

def foo(arg1, arg2, arg3):
     my_args =  find_args(foo)
     my_dict = { k: v for k,v in zip(my_args, [arg1, arg2, arg3])}
     my_str = "{arg1} went up the {arg2} hill to fetch a pail of {arg3}".format(**my_dict)
     print my_str

foo('a','b', 'c')

Will return

a went up the b hill to fetch a pail of c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM