📖
Docs
  • Hi there 👋
  • Python
    • Tutorial
      • Class
      • Context Managers
      • Iterators and Iterables and generators
      • Lambda Operator
      • Decorators
      • Lập trình Ä‘a luồng
      • Singleton
      • Logging
      • Best practices
    • Django
      • Lazy queryset
      • Sql injection
      • Transaction
    • Flask
    • Fastapi
  • Struct data and algorithms
    • Struct data
    • Algorithms
  • database
    • Nosql và RDBMS
    • Index sql
    • Inverted Index
    • Migrate database best
    • Datatype
  • Cache
    • Caching strategies
    • Cache replacement policies
  • Message queue
    • Message queue
  • Other
    • Clean code
    • Design pattern
    • Encode-decode
    • Security
    • Docker
    • Celery
  • deploy
    • Jenkins
Powered by GitBook
On this page
  • VD Context Managers
  • Cách tạo Context Managers
  1. Python
  2. Tutorial

Context Managers

VD Context Managers

with open('foo', 'w') as f:
    f.write('Hora! We opened this file')

Cách tạo Context Managers

class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        if self.file:
            self.file.close()
            
with FileManager('example.txt', 'w') as f:
    f.write('Hello, world!')
from contextlib import contextmanager
import datetime

@contextmanager
def measure_contextmanager():
    try:
        start = datetime.datetime.now()
        yield
    finally:
        end = datetime.datetime.now()
        diff = (end - start)
        print(f'Run: {diff.total_seconds()}s')
        
with measure_contextmanager() as _:
    print('test')
PreviousClassNextIterators and Iterables and generators

Last updated 2 years ago