我想在我的配置字典中有一堆生成器。所以我尝试了这个:
@yaml.register_class
class UniformDistribution:
yaml_tag = '!uniform'
@classmethod
def from_yaml(cls, a, node):
for x in node.value:
if x[0].value == 'min':
min_ = float(x[1].value)
if x[0].value == 'max':
max_ = float(x[1].value)
def f():
while True:
yield np.random.uniform(min_, max_)
g = f()
return g
但是,解析器永远不会返回,因为内部使用生成器来解析诸如&A
和*A
之类的引用。因此,类似返回(g,)
的方法是一个非常简单的解决方法,但是我更喜欢不需要在next(config['position_generator'][0])
中使用额外且非常混乱的索引0项的解决方案。
有什么想法吗?
答案 0 :(得分:0)
这个改编自a different question的包装程序完全符合我的要求。
class GeneratorWrapper(Generator):
def __init__(self, function, *args):
self.function = function
self.args = args
def send(self, ignored_arg):
return self.function(*self.args)
def throw(self, typ=None, val=None, tb=None):
raise StopIteration
@yaml.register_class
class UniformDistribution:
yaml_tag = '!uniform'
@classmethod
def from_yaml(cls, constructor, node):
for x in node.value:
value = float(x[1].value)
if x[0].value == 'min':
min_ = value
if x[0].value == 'max':
max_ = value
return GeneratorWrapper(np.random.uniform, min_, max_)