Skip to content

Instantly share code, notes, and snippets.

@AntiKnot
Created August 10, 2020 09:11
Show Gist options
  • Select an option

  • Save AntiKnot/925c2229f3d99243a6e75692fc0612c0 to your computer and use it in GitHub Desktop.

Select an option

Save AntiKnot/925c2229f3d99243a6e75692fc0612c0 to your computer and use it in GitHub Desktop.
实现上下文管理 with
import contextlib
@contextlib.contextmanager
def my_open(file_name):
# __enter__
print('open file: ', file_name, 'in_enter')
file_handler = open(file_name)
yield file_handler
# __exit__
print('close file:', file_name, 'in_exit')
file_handler.close()
return
if __name__ == '__main__':
with open('hello.txt') as f:
for line in f:
print(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment