Contenido del Curso
Python Advanced Concepts
Python Advanced Concepts
Practical Examples of Generators
Generators can be used as lightweight context managers to manage resources efficiently, such as database connections, file operations, or locking mechanisms. With the contextlib
module, generators can handle resource allocation and cleanup seamlessly.
from contextlib import contextmanager @contextmanager def database_connection(): print("Opening database connection") connection = "Database Connection" # Simulated connection try: yield connection finally: print("Closing database connection") # Using the generator as a context manager with database_connection() as conn: print(f"Using {conn}")
Processing Large Data Efficiently
Generators are ideal for building data pipelines that process large datasets lazily. Each stage of the pipeline can be implemented as a generator, enabling efficient, memory-friendly processing.
import re # Stage 1: Read lines lazily def read_lines(text): for line in text.split("\n"): yield line # Stage 2: Filter non-empty lines def filter_lines(lines): for line in lines: if line.strip(): yield line # Stage 3: Extract words lazily def extract_words(lines): for line in lines: for word in re.findall(r'\w+', line): yield word # Stage 4: Transform words to lowercase def lowercase_words(words): for word in words: yield word.lower() # Input text text = """Generators are powerful tools They allow efficient data processing This pipeline demonstrates their usage""" # Build the pipeline lines = read_lines(text) filtered = filter_lines(lines) words = extract_words(filtered) lowercased = lowercase_words(words) # Process the data print("Processed words:") for word in lowercased: print(word)
¡Gracias por tus comentarios!