Skip to content

Instantly share code, notes, and snippets.

@jimathyp
Last active August 25, 2022 23:41
Show Gist options
  • Save jimathyp/11a8c42d987944f5f24d72129dd40e2b to your computer and use it in GitHub Desktop.
Save jimathyp/11a8c42d987944f5f24d72129dd40e2b to your computer and use it in GitHub Desktop.

Python context managers

context managers provide - the 'with' construct

with blah:
  do-something()

a context manager (blah) implements enter and __exit__methods

from contextlib import AbstractContextManager

https://docs.python.org/3/library/contextlib.html

class contextlib.AbstractContextManager

An abstract base class for classes that implement object.enter() and object.exit(). A default implementation for object.enter() is provided which returns self while object.exit() is an abstract method which by default returns None. See also the definition of Context Manager Types.

New in version 3.6.

abstract base class Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass(); see the abc module documentation. Python comes with many built-in ABCs for data structures (in the collections.abc module), numbers (in the numbers module), streams (in the io module), import finders and loaders (in the importlib.abc module). You can create your own ABCs with the abc module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment