Bazman
Bazman

Reputation: 2150

Confused by the syntax used to process the argument in a Python Generator

In the function cache_gen, the argument is assigned to values as: values = source(), rather than values = source?
I realise they must be doing it to ensure that the argument becomes a generator but I have been unable to find any documentation to explain this syntax.
I just want to make sure I understand it properly.

import numpy as np

SAMPLER_CACHE = 10000

def cache_gen(source):
    values = source()
    while True:
        for value in values:
            yield value
        values = source()

if __name__ == "__main__":

    randn_gen = cache_gen(lambda: np.random.standard_normal(SAMPLER_CACHE))

Upvotes: 0

Views: 27

Answers (1)

Seth
Seth

Reputation: 2369

They are passing in a lambda as a parameter. They are calling source() to get the output of the lambda, which itself is the output of np.random.standard_normal(SAMPLER_CACHE). They are then using a generator to output all the values one at a time.

Upvotes: 1

Related Questions