【问题标题】:Why is a variable not getting assigned to when assignments exist in both clauses of an if-else block?当 if-else 块的两个子句中都存在赋值时,为什么没有为变量赋值?
【发布时间】:2019-10-26 16:21:14
【问题描述】:

假设我们有类似的东西:

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))

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

天哪……需要更多文字。

【问题讨论】:

  • r = callable(out_kids) 不仅在if 中,还有一个内部if 可能评估为假

标签: python python-3.x scope iterator iteration


【解决方案1】:

hasattr(iparent, "__iter__")True 并且in_kids != iparentFalse 时,不会分配r。您应该在if in_kids != iparent: 语句中添加一个else 块来为r 赋值。

【讨论】:

    【解决方案2】:

    更好地描述您的代码是:

    if test1:
        if test2:
            r = something
    else:
        r = something
    

    这应该让你如何得到你得到的错误一目了然。

    【讨论】:

      猜你喜欢
      • 2015-11-09
      • 2019-03-06
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 2020-01-20
      • 2021-08-13
      相关资源
      最近更新 更多