[英]Retrieve keys of output dictionary of python function without calling the function
assuming I have the following simple function假设我有以下简单的 function
def f(name: str):
print (name)
return {'x': 2, 'y': 1}
Assuming I have access to the function f
and I want to retrieve the keys of the returned value dict, without calling the function itself , is there a way to achieve this?假设我可以访问 function
f
并且我想检索返回值字典的键,而不调用 function 本身,有没有办法实现这一点?
EDIT: The expected output in this case is: ['x', 'y']
编辑:在这种情况下,预期的 output 是:
['x', 'y']
Why not annotate the return type, using a TypedDict
:为什么不使用
TypedDict
注释返回类型:
from typing import TypedDict
class F(TypedDict):
x: int
y: int
def f(name: str) -> F:
print (name)
return {'x': 2, 'y': 1}
Not only does this make it easy to get the keys in the return dictionary from outside the function:这不仅使从 function外部获取返回字典中的键变得容易:
>>> f.__annotations__['return'].__annotations__.keys()
dict_keys(['x', 'y'])
it actually allows the type to be checked , both inside:它实际上允许在内部检查类型:
def f(name: str) -> F:
return {'x': 2, 'y': 1} # OK
def g(name: str) -> F:
return {'x': 2, 'y': '1'} # wrong type
def h(name: str) -> F:
return {'x': 2, 'y': 1, 'z': 'foo'} # extra key
and outside:和外面:
x: int = f('foo')['x'] # OK
y: str = f('foo')['y'] # wrong type
z: int = f('foo')['z'] # missing key
the function (see MyPy playground ). function(参见MyPy 操场)。 Otherwise the inferred return type is just
dict[str, int]
, which can't be checked so precisely, and you have to go spelunking into f.__code__
to find the keys.否则,推断的返回类型只是
dict[str, int]
,无法如此精确地检查,您必须 go 深入f.__code__
才能找到密钥。
TLDR: Fetch the values from f.__code__.co_consts[-1]
. TLDR:从
f.__code__.co_consts[-1]
中获取值。
>>> f.__code__.co_consts[-1]
('x', 'y')
Literals are encoded in the code and constants of a function object.文字编码在 function object 的代码和常量中。 A convenient means to inspect this is to use the builtin
dis
module :一个方便的检查方法是使用内置的
dis
模块:
>>> import dis
>>> dis.dis(f)
2 0 LOAD_GLOBAL 0 (print)
2 LOAD_FAST 0 (name)
4 CALL_FUNCTION 1
6 POP_TOP
3 8 LOAD_CONST 1 (2)
10 LOAD_CONST 2 (1)
12 LOAD_CONST 3 (('x', 'y'))
14 BUILD_CONST_KEY_MAP 2
16 RETURN_VALUE
As one can see, building a dict
such as {'x': a, 'y': b, ...}
will first load the individual values, then a single tuple of all keys.如您所见,构建诸如
{'x': a, 'y': b, ...}
类的dict
将首先加载单个值,然后是所有键的单个元组。 If nothing else is loaded before returning the dict, the keys are the last constant of the function.如果在返回 dict 之前没有加载任何其他内容,则键是 function 的最后一个常量。
The code and constants of a function object is accessible for programmatic inspection. function object 的代码和常量可用于编程检查。 Fetching "the last constant of the function"
f
literally translates to f.__code__.co_consts[-1]
.获取“函数的最后一个常量”
f
字面意思是f.__code__.co_consts[-1]
。
Disclaimer: Extracting content from the code and constants of a function may be Python version dependent and especially depend on the function.免责声明:从 function 的代码和常量中提取内容可能取决于 Python 版本,尤其取决于 function。 Such an approach can be brittle and should not be used when arbitrary functions need to be processed.
这种方法可能很脆弱,不应该在需要处理任意函数时使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.