Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Functions: return vs yield/shaare/UDAb-A

  • python
  • python

Functions: return vs yield

  • 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}")
1 month ago Permalink
cluster icon
  • Read/Write Text Files : Read/Write Text Files Use open() to read/write text files with proper modes and encoding. Specify encoding='utf-8' for portability. Leverage with...
  • Parametrized Tests : Parametrized Tests Introduction Often, we need to test the same logic with different inputs and outputs, such as validating various IP address or hos...
  • Running Python modules : Running Scripts: python -m vs. python file.py The Core Difference: What is "Entry Point Zero"? The key to understanding the difference lies in the fir...
  • The Iteration Protocol : The Iteration Protocol We use for item in sequence: all the time. But how does Python get each item? Iterable: An object that can be looped over. It...
  • Tuples, sets : Tuples (tuple) Tuples are ordered, immutable sequences defined with parentheses (). Once created, their contents cannot be changed. Characteristics an...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are 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