Python: 在本地范围内执行

Python: exec in local scope

发帖前,我做了以下阅读:

但我的代码无法正常工作。

代码如下:


import string

arr = [0, 1, 2, 3, 4]
required = 4

red = ['0']
alpha = string.printable[10:62]
ss = ''
it = len(arr) - required + 1
for i in range(required):
    now = alpha[i]
    rd = '-'.join(red)
    ss += '\t' * (i + 1) + f'for {now} in range({it}-{rd}):\n'
    red.append(now)

exec('def inner_reducer():\n' + ss + '\t' * (required + 1) + f'yield {red[-1]}')


a = inner_reducer()
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())

不是直接在全局范围内写,我需要一个以arrrequired为参数的生成器,分配给生成器后,调用__next__()生成值。

任何帮助都是可观的。

@JordanBrière The code 100% works, but I need to write it into a generator, which takes an array and a number as parameter, and yields values. so I can import this function

您可以使用工厂函数。例如

import string

def make_inner_reducer_function(arr, required):
    red = ['0']
    alpha = string.printable[10:62]
    ss = ''
    it = len(arr) - required + 1
    for i in range(required):
        now = alpha[i]
        rd = '-'.join(red)
        ss += '\t' * (i + 1) + f'for {now} in range({it}-{rd}):\n'
        red.append(now)

    exec('def inner_reducer():\n' + ss + '\t' * (required + 1) + f'yield {red[-1]}')

    return locals()['inner_reducer']

f = make_inner_reducer_function([0, 1, 2, 3, 4], 4)

a = f()
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())