gpt4 book ai didi

python - 有没有办法检查函数输出是否分配给 Python 中的变量?

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:11 26 4
gpt4 key购买 nike

在 Python 中,我想编写一个函数,如果它自己调用它(主要用于交互使用或调试),它会将其结果漂亮地打印到控制台。出于这个问题的目的,假设它检查某物的状态。如果我调用

check_status()

我想看到这样的东西:

Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on

但是,如果我在变量赋值的上下文中调用它,我还希望它将输出作为列表传递:

not_robot_stat = check_status()
print not_robot_stat
>>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}

那么...有没有办法在一个函数内动态地知道它的输出是否正在被赋值?我希望能够在不诉诸参数传递或为此编写另一个函数的情况下做到这一点。我用 Google 搜索了一下,据我所知,我似乎不得不求助于字节码。真的有必要吗?

最佳答案

新解决方案

这是一个新的解决方案,它通过检查自己的字节码来检测函数的结果何时用于赋值。没有完成字节码编写,它甚至应该与 future 版本的 Python 兼容,因为它使用操作码模块进行定义。

import inspect, dis, opcode

def check_status():

try:
frame = inspect.currentframe().f_back
next_opcode = opcode.opname[ord(frame.f_code.co_code[frame.f_lasti+3])]
if next_opcode == "POP_TOP":
# or next_opcode == "RETURN_VALUE":
# include the above line in the if statement if you consider "return check_status()" to be assignment
print "I was not assigned"
print "Pretty printer status check 0.02v"
print "NOTE: This is so totally not written for giant robots"
return
finally:
del frame

# do normal routine

info = {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}

return info

# no assignment
def test1():
check_status()

# assignment
def test2():
a = check_status()

# could be assignment (check above for options)
def test3():
return check_status()

# assignment
def test4():
a = []
a.append(check_status())
return a

解决方案一

这是在 python -i 或 PDB 下调试时检测何时调用函数的旧解决方案。

import inspect

def check_status():
frame = inspect.currentframe()
try:
if frame.f_back.f_code.co_name == "<module>" and frame.f_back.f_code.co_filename == "<stdin>":
print "Pretty printer status check 0.02v"
print "NOTE: This is so totally not written for giant robots"
finally:
del frame

# do regular stuff
return {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}

def test():
check_status()


>>> check_status()
Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}

>>> a=check_status()
Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots

>>> a
{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}

test()
>>>

关于python - 有没有办法检查函数输出是否分配给 Python 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/813882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com