获取传递给函数的所有参数和值 [英] Getting all arguments and values passed to a function

查看:69
本文介绍了获取传递给函数的所有参数和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 函数 fetch_data,它会访问远程 API,获取一些数据,然后将它包装在响应对象中返回.它看起来有点像下面:

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

现在,响应数据可能会显示我有更多数据,请使用递增的 page 参数给我打电话以获得更多数据".因此,我基本上想在响应对象中存储方法调用"(函数,参数),这样我就可以有一个 Response.get_more() 来查看存储的函数和参数,并使用(几乎)相同的参数再次调用该函数,返回一个新的 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

现在如果 fetch_data 被定义为 fetch_data(*args, **kwargs) 我可以只存储 (fetch_data, args, kwargs)response 中.但是我有 selffoobarbaz 需要担心 - 我可以只存储 (fetch_data, foo, bar, baz, kwargs) 但这是非常不受欢迎的重复量.

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.

本质上,我试图找出如何从函数内部获取完全填充的 *args**kwargs,包括函数的命名参数.

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.

推荐答案

从本质上讲,我正在努力研究如何从函数内部获取完全填充的 *args 和 **kwargs,包括函数的命名参数.

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.

如何通过函数开头的locals()保存参数?

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')

它给出了这个输出:

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'}}

帽子提示:https://stackoverflow.com/a/3137022/2829764

这篇关于获取传递给函数的所有参数和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆