← Hudson River Trading Interview Insights

Hudson River Trading·Software Engineer·Technical Phone Screen·Senior

SeniorPrefer not to say
May 2026

Summary

Technical phone screen for a full-stack role at Hudson River Trading, focused almost entirely on Python context managers. Pretty deep dive for a single topic, they really wanted to see if you understood the mechanics under the hood, not just that you'd used `with` statements before.

Questions Asked (5)

Q1

Walk me through how the context manager protocol works in Python. What do __enter__ and __exit__ actually do, and what happens when an exception is raised inside a `with` block?

Technical Trade-offsAlgorithms & Data Structures
Author's notes

This part went okay.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by defining the context manager protocol as a way to manage resources with guaranteed cleanup, then explain the roles of __enter__ and __exit__ in detail. Walk through a concrete example, including what happens when an exception is raised inside the with block, and highlight how __exit__ can suppress exceptions.

Pro tip: Emphasize that __exit__ returning True suppresses the exception, which is a common pitfall; also mention that context managers are not just for resource cleanup but can be used for any setup/teardown logic, and that the contextlib module provides utilities like @contextmanager to simplify creation.

1. Define the protocol

Explain that a context manager is an object that defines __enter__ and __exit__ methods, enabling the with statement to manage resources.

2. Describe __enter__

Detail that __enter__ is called when entering the with block, and its return value is assigned to the variable after 'as' (if any).

3. Describe __exit__

Explain that __exit__ is called when exiting the block, with arguments (exc_type, exc_val, exc_tb) that are None if no exception occurred; it handles cleanup and can suppress exceptions by returning True.

4. Explain exception handling

Walk through what happens when an exception is raised inside the with block: __exit__ is called with the exception details, and if it returns True, the exception is suppressed; otherwise, it propagates.

5. Provide an example

Give a concrete example, such as a file context manager, to illustrate the flow and exception handling.

Key Points to Mention

  • The with statement calls __enter__ and __exit__ on the context manager object.
  • __enter__ can return a value that is bound to the variable after 'as'.
  • __exit__ receives exception type, value, and traceback; if no exception, all are None.
  • __exit__ returning True suppresses the exception; returning False or None lets it propagate.
  • Context managers are commonly used for resource management (files, locks, connections).
  • The contextlib module provides @contextmanager decorator to create context managers from generator functions.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q2

Implement a context manager as a class using __enter__ and __exit__, then implement the same thing using contextlib.contextmanager with a generator. What are the differences?

Technical Trade-offsSystem Design
Author's notes

The class-based version was fine.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by implementing the class-based context manager with __enter__ and __exit__, then show the equivalent using @contextmanager and a generator. Compare them across dimensions like boilerplate, exception handling, reusability, and state management, emphasizing when each is preferable.

Pro tip: Mention that @contextmanager is built on top of the class-based protocol, so understanding the underlying mechanics helps you debug edge cases like exceptions thrown inside the with block.

1. Implement class-based context manager

Define a class with __enter__ that acquires the resource and returns it, and __exit__ that releases the resource and handles exceptions.

2. Implement generator-based context manager

Use @contextmanager to decorate a generator function that yields the resource, with setup before yield and teardown in a finally block.

3. Compare exception handling

Explain that __exit__ receives exception details and can suppress exceptions by returning True, while @contextmanager uses try/except/finally around yield and can suppress by catching the exception.

4. Discuss reusability and state

Highlight that class-based managers are reusable instances with persistent state, while generator-based managers are single-use and state is local to the generator.

5. Summarize trade-offs and use cases

Conclude that @contextmanager reduces boilerplate for simple cases, but class-based is better for complex logic, multiple entry points, or when you need to inherit and extend.

Key Points to Mention

  • Class-based requires defining __enter__ and __exit__ methods; generator-based uses @contextmanager and a single yield.
  • __exit__ receives exc_type, exc_val, exc_tb and can suppress exceptions by returning True; @contextmanager can suppress by catching the exception inside the generator.
  • Generator-based context managers are single-use; class-based instances can be reused if designed to be reentrant.
  • Class-based allows additional methods and attributes, making it more extensible and suitable for complex resource management.
  • @contextmanager is implemented using the class-based protocol internally, so it's not a replacement but a convenience.
  • Both ensure cleanup, but generator-based relies on the generator's finally block, which runs even if an exception occurs.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q3

Write a timing context manager that records and prints elapsed time when the block finishes.

Algorithms & Data Structures
Author's notes

Easy one.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Implement a context manager class with __enter__ and __exit__ methods that record the start time on entry and compute and print the elapsed time on exit. Use time.perf_counter for high-resolution timing and ensure the elapsed time is printed even if an exception occurs. Optionally, support reuse and nesting by storing start time as an instance attribute.

Pro tip: Mention that time.perf_counter is preferred over time.time for measuring short durations because it's monotonic and has the highest available resolution. Also, note that printing in __exit__ ensures timing is reported even when exceptions propagate, which is crucial for debugging.

1. Define the context manager class

Create a class, e.g., Timer, with __init__ that optionally accepts a label. This sets up the object to be used in a with statement.

2. Implement __enter__

In __enter__, record the start time using time.perf_counter() and return self (or the timer object). This allows the with block to access the timer if needed.

3. Implement __exit__

In __exit__, compute elapsed = time.perf_counter() - start, print it (with label if provided), and return False to propagate exceptions. Ensure printing happens regardless of exceptions.

4. Handle exceptions and reusability

Discuss that __exit__ receives exception info; we can log it but still print elapsed time. Also, note that the timer can be reused if start time is reset in __enter__.

5. Provide example usage

Show a simple with Timer('my_block'): block of code, and mention output format like 'my_block elapsed: 0.1234 seconds'.

Key Points to Mention

  • Use time.perf_counter() for high-resolution, monotonic timing.
  • Implement __enter__ to record start time and return self.
  • Implement __exit__ to compute and print elapsed time, and return False to propagate exceptions.
  • Ensure elapsed time is printed even if an exception occurs inside the block.
  • Support optional label for identifying different timers.
  • Consider reusability by resetting start time in __enter__.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q4

How would you use contextlib.ExitStack to handle nested or re-entrant context managers? Give a concrete scenario where you'd need it.

System DesignTechnical Trade-offs
Author's notes

This is where I got a little lost.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by explaining that ExitStack manages a dynamic stack of context managers, allowing you to enter them programmatically and ensuring they are all properly exited in reverse order. Then, describe a concrete scenario where the number or nesting of context managers isn't known until runtime, such as acquiring multiple resources in a loop or conditionally entering contexts. Finally, highlight how ExitStack simplifies cleanup and avoids deeply nested with statements.

Pro tip: Mention that ExitStack supports re-entrant context managers by allowing the same context manager to be entered multiple times, and that you can use callbacks for custom cleanup. Also, note that ExitStack is not thread-safe, so synchronization is needed in concurrent scenarios.

1. Define ExitStack and its purpose

Explain that contextlib.ExitStack is a context manager designed to manage a stack of other context managers or cleanup callbacks, entering them dynamically and exiting them in LIFO order.

2. Explain how to use ExitStack for nested contexts

Describe the pattern: create an ExitStack instance, then use enter_context() to add context managers as needed, and optionally callback() for custom cleanup. The stack ensures all are exited even if exceptions occur.

3. Address re-entrant context managers

Clarify that re-entrant context managers can be entered multiple times, and ExitStack handles this by tracking each entry separately, exiting each in reverse order.

4. Provide a concrete scenario

Give a specific example, such as opening multiple files whose names are determined at runtime, or acquiring multiple locks in a loop, where the number of resources is not known in advance.

5. Discuss trade-offs and alternatives

Mention that while ExitStack adds flexibility, it can obscure control flow compared to explicit with statements. Also note that it's not thread-safe and may require additional synchronization in concurrent environments.

Key Points to Mention

  • ExitStack allows dynamic entering of context managers via enter_context() and callbacks via callback().
  • It ensures proper cleanup in reverse order, even when exceptions occur.
  • Re-entrant context managers can be entered multiple times, and ExitStack tracks each entry.
  • Concrete scenario: managing multiple resources like files, locks, or network connections where the number is determined at runtime.
  • Trade-off: ExitStack can make code less readable and is not thread-safe.
  • Alternative: explicit nested with statements for static cases, or AsyncExitStack for async contexts.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q5

What are the pitfalls of context managers in practice? Things like idempotency of __exit__, deciding when to suppress vs re-raise exceptions, and forgetting cleanup on exceptions.

Technical Trade-offsAPI & Integrations
Author's notes

They basically asked me to enumerate failure modes.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Acknowledge that context managers are powerful but have subtle pitfalls, then systematically discuss the key issues: idempotency of __exit__, exception suppression vs. re-raising, and cleanup guarantees. Use concrete examples to illustrate each pitfall and how to avoid them, emphasizing careful design and testing.

Pro tip: Mention that context managers should be designed to be idempotent and that suppressing exceptions should be done sparingly and with clear intent, as it can hide bugs. Also, note that using contextlib.contextmanager can simplify writing context managers but requires careful handling of exceptions in the generator.

1. Define context managers and their purpose

Briefly explain that context managers ensure proper resource management via __enter__ and __exit__, commonly used with the 'with' statement.

2. Discuss idempotency of __exit__

Explain that __exit__ may be called multiple times in some scenarios (e.g., nested with statements or manual calls), so it should be idempotent to avoid double-cleanup issues.

3. Address exception suppression vs. re-raising

Describe that __exit__ can suppress exceptions by returning True, but this should be done only when the context manager can meaningfully handle the exception; otherwise, re-raise to avoid masking errors.

4. Highlight cleanup guarantees and pitfalls

Emphasize that cleanup in __exit__ must run even if exceptions occur, but forgetting to handle exceptions properly can lead to resource leaks or inconsistent state.

5. Provide best practices and examples

Suggest using contextlib.contextmanager for simpler cases, ensuring __exit__ is robust, and testing edge cases like exceptions during cleanup.

Key Points to Mention

  • Idempotency: __exit__ should be safe to call multiple times without adverse effects.
  • Exception suppression: returning True from __exit__ suppresses exceptions; use judiciously to avoid hiding bugs.
  • Cleanup on exceptions: ensure __exit__ always performs cleanup, even if an exception occurs in the with block.
  • Nested context managers: order of exit is reverse of entry; ensure each handles its own cleanup.
  • contextlib.contextmanager: simplifies writing context managers but requires try/finally in the generator.
  • Testing: write tests for edge cases like exceptions during cleanup and multiple exits.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.