获取内部函数 [英] Get kwargs Inside Function

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

问题描述

如果我有这样的python函数:

def some_func(arg1, arg2, arg3=1, arg4=2):

有没有一种方法可以确定关键字从函数内部传递了哪些参数?

编辑

对于那些问我为什么需要这个的人,我没有真正的理由,它出现在对话中,好奇心使我变得更好.

解决方案

否,无法在带有此签名的Python代码中执行此操作-如果需要此信息,则需要更改函数的签名.

如果您查看Python C API,您会发现将参数传递给普通Python函数的实际方式始终是元组加dict-即直接反映签名的方式*args, **kwargs.然后将该元组和字典解析为特定的位置args,并在签名中命名它们,即使它们是通过名称传递的,并且*a**kw(如果存在)仅从该解析中获取溢出",如果有的话-仅在这一点上您的Python代码才得到控制,然后您所请求的信息( 如何传递各种args)就不再存在了.

因此,要获取您所需的信息,请将签名更改为*a, **kw并进行自己的解析/验证-这是从鸡蛋到煎蛋"的工作,即一定数量的工作,但肯定可行,而您正在寻找的是从煎蛋卷回到鸡蛋"……简直不可行;-).

If I have a python function like so:

def some_func(arg1, arg2, arg3=1, arg4=2):

Is there a way to determine which arguments were passed by keyword from inside the function?

EDIT

For those asking why I need this, I have no real reason, it came up in a conversation and curiosity got the better of me.

解决方案

No, there is no way to do it in Python code with this signature -- if you need this information, you need to change the function's signature.

If you look at the Python C API, you'll see that the actual way arguments are passed to a normal Python function is always as a tuple plus a dict -- i.e., the way that's a direct reflection of a signature of *args, **kwargs. That tuple and dict are then parsed into specific positional args and ones that are named in the signature even though they were passed by name, and the *a and **kw, if present, only take the "overflow" from that parsing, if any -- only at this point does your Python code get control, and by then the information you're requesting (how were the various args passed) is not around any more.

To get the information you requested, therefore, change the signature to *a, **kw and do your own parsing/validation -- this is going "from the egg to the omelette", i.e. a certain amount of work but certainly feasible, while what you're looking for would be going "from the omelette back to the egg"... simply not feasible;-).

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

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