首页 > 解决方案 > 当 if-else 块的两个子句中都存在赋值时,为什么没有为变量赋值?

问题描述

假设我们有类似的东西:

if True:
    r = 0
else:
    r = 1
print(r)

为什么我们会得到UnboundLocalError: local variable 'r' referenced before assignment

实际代码如下所示:

def rasterize_dot_verify_args(callable, parent):

    if not hasattr(callable, "__call__"):
        raise ValueError()
    import inspect
    siggy = inspect.signature(callable)
    if (len(siggy.parameters) > 1):
        raise ValueError()

def rasterize(callable, xparent, make_copy :bool = False):
    rasterize_dot_verify_args(callable, xparent)

    iparent = xparent
    if make_copy:
        import copy
        iparent = copy.deepcopy(xparent)

    if hasattr(iparent, "__iter__"):
        in_kids = iter(iparent)
        if in_kids != iparent:
            lamby = lambda p, *, c=callable: rasterize(c, p)
            out_kids = map(lamby, in_kids)

            # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            r = callable(out_kids)  # !!!!!!!!!!!!!!!!!!!!
            # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    else:
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        r = iparent  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    return r

import itertools as itts
sixify = lambda obj, *, itts=itts: itts.repeat(obj, 6)
inputs = map(sixify, range(1, 5))

# inputs = (_ for _ in [
#      itts.repeat(1, 6),
#      itts.repeat(2, 6),
#      itts.repeat(3, 6),
#      itts.repeat(4, 6)
# ])

print(rasterize(list, inputs))

我不得不在这里添加一点文字,因为“看起来您的帖子主要是代码;请添加更多细节。”

哦,亲爱的....需要更多的文字。

标签: pythonpython-3.xscopeiteratoriteration

解决方案


rhasattr(iparent, "__iter__")当isTruein_kids!= iparentis时不会被赋值False。您应该else在语句中添加一个块if in_kids != iparent:来分配r一个值。


推荐阅读