AI engineering glossary · Python advanced

What is __enter__ and __exit__?

__enter__ and __exit__: The pair of special methods that make a class usable as a context manager. __enter__ runs as the block starts and returns the value bound after 'as'; __exit__ runs at the end and receives any exception raised.

Level: advancedTopic: Python advanced

__enter__ and __exit__: an example

class Timer: __enter__ records the start time and __exit__ prints elapsed seconds after the with block ends.

Related terms

More Python advanced terms

Where you learn it

__enter__ and __exit__ is part of the AI Engineering Program, which teaches it with notes, a hands-on lab and an exam. The first lesson is free.

Before you go

Take the cheat sheet with you

One free PDF: the key AI-engineering terms, formulas and Python idioms. No spam; unsubscribe any time.