(免责声明:我不建议在生产质量代码中使用恶魔般的技术。此答案中的所有内容可能无法在与我不同的计算机、与我不同的 Python 版本或非 CPython 发行版上运行,明天早上可能就不行了。)
也许您可以通过检查调用帧的字节码来做到这一点。如果我正确阅读了bytecode guide,则多个分配由指令UNPACK_SEQUENCE 或UNPACK_EX 处理,具体取决于目标列表是否具有星号名称。这两条指令都在其参数中提供了有关目标列表形状的信息。
您可以编写您的恶魔函数来爬升帧层次结构,直到找到调用帧,并检查出现在代表赋值右侧的FUNCTION_CALL 之后的字节码指令。 (这是假设您对MyObject() 的调用是语句右侧的唯一内容)。然后你可以从指令的参数中提取目标列表大小并返回它。
import inspect
import dis
import itertools
def diabolically_retrieve_target_list_size():
#one f_back takes us to `get_diabolically_sized_list`'s frame. A second one takes us to the frame of the caller of `get_diabolically_sized_list`.
frame = inspect.currentframe().f_back.f_back
#explicitly delete frame when we're done with it to avoid reference cycles.
try:
#get the bytecode instruction that immediately follows the CALL_FUNCTION that is executing right now
bytecode_idx = frame.f_lasti // 2
unresolved_bytecodes = itertools.islice(dis.get_instructions(frame.f_code), bytecode_idx+1, bytecode_idx+3)
next_bytecode = next(unresolved_bytecodes)
if next_bytecode.opname == "UNPACK_SEQUENCE": #simple multiple assignment, like `a,b,c = ...`
return next_bytecode.arg
elif next_bytecode.opname == "EXTENDED_ARG": #multiple assignment with splat, like `a, *b, c = ...`
next_bytecode = next(unresolved_bytecodes)
if next_bytecode.opname != "UNPACK_EX":
raise Exception(f"Expected UNPACK_EX after EXTENDED_ARG, got {next_bytecode.opname} instead")
args_before_star = next_bytecode.arg % 256
args_after_star = next_bytecode.arg >> 8
return args_before_star + args_after_star
elif next_bytecode.opname in ("STORE_FAST", "STORE_NAME"): #single assignment, like `a = ...`
return 1
else:
raise Exception(f"Unrecognized bytecode: {frame.f_lasti} {next_bytecode.opname}")
finally:
del frame
def get_diabolically_sized_list():
count = diabolically_retrieve_target_list_size()
return list(range(count))
a,b,c = get_diabolically_sized_list()
print(a,b,c)
d,e,f,g,h,i = get_diabolically_sized_list()
print(d,e,f,g,h,i)
j, *k, l = get_diabolically_sized_list()
print(j,k,l)
x = get_diabolically_sized_list()
print(x)
结果:
0 1 2
0 1 2 3 4 5
0 [] 1
[0]