Skip to content

Instantly share code, notes, and snippets.

@christianmlong
Created June 17, 2024 02:27
Show Gist options
  • Save christianmlong/7be6be89cf8ea65db6e14ea2b660f637 to your computer and use it in GitHub Desktop.
Save christianmlong/7be6be89cf8ea65db6e14ea2b660f637 to your computer and use it in GitHub Desktop.
# Expanded version of Glyph's example at
# https://mastodon.social/@glyph/112628092787725236
def loop():
for number in range(10):
def closure():
print("Inside the closure")
return number
print("Before yield")
yield closure
print("After yield")
# eagerly = [each() for each in loop()]
print("\nEagerly evaluate the closures, lazily iterate the generator\n")
generator = loop()
for each in generator:
print(f"Function {each}")
print(f"Result {each()}")
# lazily = [each() for each in list(loop())]
print("\nLazily evaluate the closures, eagerly iterate the generator\n")
evaluated = list(loop())
for each in evaluated:
print(f"Function {each}")
print(f"Result {each()}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment