Interview Q&A / Python

INTERVIEW Q&A · 81 QUESTIONS

Python interview questions

Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.

  1. Why do we use the with statement when working with files?

    with guarantees the file is closed when the block ends, even if an exception occurs. It works through a context manager, an object with __enter__ and __exit__ methods, so cleanup does not depend on remembering to call close().

    BeginnerQuick answer1 min read
  2. How do you write your own context manager in Python?

    Either write a class with __enter__ and __exit__ methods, or write a generator function decorated with @contextlib.contextmanager that yields once. Code before the yield is setup and code after it is cleanup, which should sit in a finally block.

    IntermediateQuick answer1 min read