【发布时间】: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