Reputation: 3313
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,
Upvotes: 2
Views: 242
Reputation: 77337
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())
Upvotes: 3
Reputation: 35109
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
Upvotes: 0
Reputation: 7706
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.
Upvotes: 2