为了账号安全,请及时绑定邮箱和手机立即绑定

动态响应解包赋值语句

动态响应解包赋值语句

LEATH 2022-01-05 10:46:01
在解包赋值语句中,被赋值的对象能否检查它被赋值的变量数量?class MyObject:    def __iter__(self):        n = some_diabolical_hack()        print(f"yielding {n} vals")        return iter(["potato"]*n)就像是:>>> x, y = MyObject()yielding 2 vals>>> a, b, c = MyObject()yielding 3 vals在更一般的情况下,它可以内省target_list分配中使用的“形状”吗?>>> first, *blob, d[k], (x, y), L[3:7], obj.attr, last = MyObject()unpacking to <_ast.Tuple object at 0xcafef00d>示例潜在用例:MagicMock()当用于修补赋值语句右侧的某个对象时,不需要预先配置固定迭代长度的改进。
查看完整描述

2 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

您可以使用回溯模块:


import traceback


def diabolically_invoke_traceback():

    call = traceback.extract_stack()[-2]

    print call[3]

    unpackers = call[3].split('=')[0].split(',')

    print len (unpackers)

    return range(len(unpackers))


In [63]: a, b, c = diabolically_invoke_traceback()

a, b, c = diabolically_invoke_traceback()

3


In [64]: a

Out[64]: 0


In [65]: b

Out[65]: 1


In [66]: c

Out[66]: 2


查看完整回答
反对 回复 2022-01-05
?
慕勒3428872

TA贡献1848条经验 获得超6个赞

也许您可以通过检查调用帧的字节码来做到这一点。如果我正确阅读了字节码指南,多重赋值由指令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]


查看完整回答
反对 回复 2022-01-05
  • 2 回答
  • 0 关注
  • 197 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信