Skip to content

Instantly share code, notes, and snippets.

@omry
Created June 23, 2020 23:24
Show Gist options
  • Save omry/8b84f8f77ef431e6a50d8a892f865f5c to your computer and use it in GitHub Desktop.
Save omry/8b84f8f77ef431e6a50d8a892f865f5c to your computer and use it in GitHub Desktop.
from contextlib import contextmanager
from typing import Any
@contextmanager
def foo() -> Any:
print("1 before")
yield
print("1 after")
class dual_foo:
def __init__(self, *args, **kwargs):
print("run")
def __enter__(self, *args, **kwargs):
...
def __exit__(self, exc_type, exc_val, exc_tb):
print("cleanup")
if __name__ == "__main__":
print("== context call:")
with dual_foo():
pass
print("== standalone call:")
dual_foo()
@omry
Copy link
Author

omry commented Jun 23, 2020

== context call:
run
cleanup
== standalone call:
run

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