Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/Implement a context manager class for a sequence generator using __enter__ and __exit__

Implement a context manager class for a sequence generator using __enter__ and __exit__

Python/Codingeasy2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

A context manager class, implemented with enter and exit , provides a robust way to manage resources by ensuring setup and teardown operations are executed reliably, even in the presence of errors.…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
Moonfare

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like Moonfare. While less common, it tests deeper understanding that distinguishes strong candidates.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
383 wordsIncludes code

A context manager class, implemented with __enter__ and __exit__, provides a robust way to manage resources by ensuring setup and teardown operations are executed reliably, even in the presence of errors. For a sequence generator, this means guaranteeing proper initialization of the generator's state and finalization of any associated resources.

Mechanics and Why

The __enter__ method is invoked upon entering the with block. It should perform any necessary setup, such as initializing the sequence's starting point, opening a file handle, or establishing a database connection. This method must return the resource to be used within the block (often self for class-based context managers). The __exit__ method is called upon exiting the with block, regardless of whether the exit was normal or due to an exception. It receives the exception type, value, and traceback as arguments. Returning True from __exit__ suppresses the exception, while False (or None) allows it to propagate.

This pattern guarantees resource cleanup, preventing leaks and improving system stability. In data engineering, this is critical for managing connections to data warehouses (e.g., Snowflake, BigQuery), file systems (e.g., S3, HDFS), or stream processors (e.g., Kafka consumers), ensuring connections are closed, buffers flushed, or temporary files deleted. This reliability is paramount in production data pipelines where resource contention and stability are key concerns.

Example: Stateful Sequence Generator

For a sequence generator, __enter__ might initialize the starting point and potentially log the start of generation, while __exit__ could log statistics, reset state, or close an underlying data source.
class SequenceGenerator:
    def __init__(self, start, stop):
        self.current = start
        self.stop = stop
    def __enter__(self):
        print(f"Entering sequence generator context: {self.current} to {self.stop}")
        return self # The object itself is the iterable resource
    def __iter__(self):
        return self
    def __next__(self):
        if self.current < self.stop:
            value = self.current
            self.current += 1
            return value
        raise StopIteration
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"Exiting sequence generator context. Last value generated: {self.current - 1}")
        if exc_type:
            print(f"An exception occurred during generation: {exc_val}")
            # Production note: Log the exception here, don't just print.
        return False # Propagate exceptions by default

In the interview, also mention…

Discuss the contextlib.contextmanager decorator as a more concise, function-based alternative for simpler context managers, especially when wrapping existing generators or functions that yield a single resource. This can reduce boilerplate for less complex use cases.
⚡
Pro Tip

Pro-Move: @contextmanager. Red Flag: Not handling exceptions.

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer