Regular functions execute immediately, run to completion, and return a single value (or None).
Generator functions return an iterator immediately; their body runs incrementally as values are requested.
Understanding this distinction is critical for choosing between eager and lazy workflows.
Regular Function (return) Recap
Calling a regular function runs its entire body before returning.
A single return exits the function and discards all local state.
Useful when you need to compute and return a complete result at once.
def get_list_of_servers():
print("Regular function started.")
servers = []
for i in range(3):
server_name = f"server-{i}"
print(f"\tAdding {server_name}")
servers.append(server_name)
print("Regular function finished.")
return servers
servers = get_list_of_servers()
print(f"Returned list: {servers}")
Generator Function (yield) Recap
Calling a generator function returns a generator object without running its body.
Each yield returns one value and pauses, preserving local variables until the next request.
Ideal for producing sequences lazily, especially when the full list is large or unbounded.
def yield_servers(count):
print("Generator function started.")
for i in range(count):
server_name = f"server-{i}"
print(f"\tYielding {server_name}")
yield server_name
print("Generator function finished.")
servers_gen = yield_servers(3)
for server in servers_gen:
print(f"Server received: {server}")
FoldFold allExpandExpand allAre you sure you want to delete this link?Are you sure you want to delete this tag?
The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community