English 中文(简体)
将所有参数和值传递到函数
原标题:Getting all arguments and values passed to a function
  • 时间:2012-05-23 16:54:11
  •  标签:
  • python

我有一个 Python 函数, < code> fetch_ data , 它可以去和点击远程 API, 抓取一些数据, 返回在响应对象中包裹的数据。 它看起来有点像下面 :

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

现在, 回复数据可能表示“ 我有更多的数据, 以递增 < code> page 参数给我打电话以获得更多 。 因此, 我基本上喜欢在响应对象中存储“ 方法呼叫”( 功能、 参数), 这样我就可以有一个 < code> Response. get_ more () 来查看存储的函数和参数, 并且用( 几乎) 相同的参数再次调用该函数, 返回新的 < code> Response

现在,如果将 fetch_data 定义为 fetch_data(* args,**kwargs) ,我可以将 (fetch_data, args, kwargs) 存储在 < code> 回复 中,但我有 self , , bar < baz 来担心 -- -- 我可以只存储 (fetch_data, foo, bar, baz, kwargs) ,但重复的次数非常不可取。

基本上,我正在设法在函数内找到一个完全有人居住的 ,包括指定的参数。

问题回答

从根本上说,我正在设法从一个函数中找到一个完全人口稠密的“args”和“**kwargs”,包括指定的参数。

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

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

不是我想做的,但你可以使用 inspect. 签名 来探究你的方法所采取的论点:

>>> import inspect
>>> def foobar(foo, bar, baz):
...     return inspect.signature(foobar)
... 
>>> foobar(1, 2, 3)
<Signature (foo, bar, baz)>

返回的 < a href=> https://docs.python.org/3/library/ inspect.html#inspect.html#inspect.Signature" rel="noreferr"\\code>Signature prignature 中包含有命令的参数集合("https://docs.python.org/3/library/inspet.html#inspect.Signatrial.pareters" rel=“noreferr"\code>>.paramerts 属性 ,然后可以与locals()

>>> def foobar(foo, bar, baz):
...     sig, foobar_locals = inspect.signature(foobar), locals()
...     return [foobar_locals[param.name] for param in sig.parameters.values()]
...
>>> foobar(1, 2, 3)
[1, 2, 3]

然而,你只需要在做高级功能装饰师时 使用这样的魔法。 我认为它在这里太过杀伤力了。

我不确定这是你想要的,但 locals () 提供了本地变量的字典。

>>> def foo(bar, toto):
...     print(locals())
...
>>> foo(3, sometext )
{ toto :  sometext ,  bar : 3}

我认为,一个更加多的波音法就是将您的功能转换成一个生成器,只要服务器不断返回数据,就可以获取和 yeld 数据。

这应该能产生整齐的代码 并且能让你绕开 保护反复辩论的所有复杂问题 (Python会神奇地为你做:-) )

import inspect

def f(x, y):
    print(
        inspect.getargvalues(inspect.currentframe())
    )

f(1, 2)

Result:
ArgInfo(args=[ x , y ], varargs=None, keywords=None, locals={ y : 2, x : 1})

kwargs 将不会有 foo, bar 或 bad 作为密钥, 所以您可以在 kwargs 和 just stready (fet_ data, kwargs) 中添加这些条目( w/ 他们的值) 。

我认为最简单/最清洁的方法(... ughh"pythonic") 就是使用一个装饰功能... 不需要使用“ 检查” 或迭代于本地() -- 直接从装饰功能中抓取它们。 尝试一下 :

def call_info(func: callable):
    def wrapper(*args, **kwargs):
        print(f Calling {func} with args: {args}, kwargs: {kwargs} )
        return func(*args, **kwargs)
    return wrapper

@call_info
def test_func(name, *args, size: int = 2, cheese: bool = True, **kwargs):
    print( nothing to see here... )
    print(f but if you wanted to know.... name={name}, args={args}, size=size}, cheese={cheese}, kwargs={kwargs} )

test_func(44)
test_func(name= hello , size=4, cheese=False)

将打印像这样的东西:

Calling <function test_func at 0x0000015614079E40> with args: (44,), kwargs: {}
nothing to see here...
but if you wanted to know.... name=44, args=(), size=2, cheese=True, kwargs={}
Calling <function test_func at 0x0000015614079E40> with args: (), kwargs: { name :  hello ,  size : 4,  cheese : False}
nothing to see here...
but if you wanted to know.... name=hello, args=(), size=4, cheese=False, kwargs={}

您可以将@call_info 装饰器添加到您想要查看已传递变量的任何方法/函数中。 在主函数调用之前/之后, 请对变量做任何您喜欢做的操作... 只要修改包装即可 。

这里有一个相当不错的链接 描述如何在这里使用装饰器:

< a href=> https://realpython.com/primer-on-python- decorators/" rel="不跟随 nofollow noreferrer" > https://realpython.com/primer-on-python- decorators/

Python文件也对此作了说明:

https://docs.python.dosainion.de/3/glossary.html#term-decorator

尝试此 :

def my_func(a, *args, **kwargs):
    v = locals()
    allargs = [v[i] for i in my_func.__code__.co_varnames if i in v and i not in ( args , kwargs )]
    allargs.extend(args)
    return allargs, kwargs

Listargsallgs 组合了所需的参数和可选参数。 代码必须放在函数开始处, 至少 v = locals () 。

>>> def fun(a,b,c):
...   print(locals())
... 
>>> fun(1,2,3)
{ a : 1,  b : 2,  c : 3}




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签