Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

python - Getting all arguments and values passed to a function

I have a Python function, fetch_data, that goes and hits a remote API, grabs some data, and returns it wrapped in a response object. It looks a bit like the below:

def fetch_data(self, foo, bar, baz, **kwargs):
    response = Response()
    # Do various things, get some data
    return response

Now, it's possible that the response data says "I have more data, call me with an incremented page parameter to get more". Thus, I'd essentially like to store "The Method Call" (function, parameters) in the response object, so I can then have a Response.get_more() which looks at the stored function and parameters, and calls the function again with (almost) the same parameters, returning a new Response

Now if fetch_data were defined as fetch_data(*args, **kwargs) I could just store (fetch_data, args, kwargs) in response. However I have self, foo, bar and baz to worry about - I could just store (fetch_data, foo, bar, baz, kwargs) but that's a highly undesirable amount of repetition.

Essentially, I'm trying to work out how to, from within a function, get a completely populated *args and **kwargs, including the function's named parameters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Essentially, I'm trying to work out how to, from within a function, get a completely populated *args and **kwargs, including the function's named parameters.

How about saving the arguments via locals() at the beginning of the function?

def my_func(a, *args, **kwargs):
    saved_args = locals()
    print("saved_args is", saved_args)
    local_var = 10
    print("saved_args is", saved_args)
    print("But locals() is now", locals())

my_func(20, 30, 40, 50, kwarg1='spam', kwarg2='eggs')

It gives this output:

saved_args is {'a': 20, 'args': (30, 40, 50), 'kwargs': {'kwarg1': u'spam', 'kwarg2': u'eggs'}}
saved_args is {'a': 20, 'args': (30, 40, 50), 'kwargs': {'kwarg1': u'spam', 'kwarg2': u'eggs'}}
But locals is now {'a': 20, 'saved_args': {...}, 'args': (30, 40, 50), 'local_var': 10, 'kwargs': {'kwarg1': u'spam', 'kwarg2': u'eggs'}}

Hat tip: https://stackoverflow.com/a/3137022/2829764


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...