Python keyword : with - zpion-id/d GitHub Wiki

Table of Contents

Statement with

with A() as a, B() as b:
    pass
# a simple file writer object

class MessageWriter(object):
	def __init__(self, file_name):
		self.file_name = file_name
	
	def __enter__(self):
		self.file = open(self.file_name, 'w')
		return self.file

	def __exit__(self):
		self.file.close()

# using with statement with MessageWriter

with MessageWriter('my_file.txt') as xfile:
	xfile.write('hello world')

Agar kelas memenuhi syarat sebagai manajer konteks, kelas perlu menerapkan dua metode ini:

  • __enter__()
  • __exit__()
Kelas atau fungsi yang mendukung with tersebut dikenal sebagai manajer konteks .

Setelah menerapkan metode ini, Anda dapat menggunakan with pada objek kelas.

  • Saat Anda memanggil with, metode () akan dipanggil.
  • Saat Anda keluar dari ruang lingkup with blok, metode () akan dipanggil.
from contextlib import contextmanager

@contextmanager
def my_open(name):
    try:
        file = open(name, "w")
        yield file
    finally:
        file.close()

with my_open("example.txt") as file:
    file.write("hello world")
  1. https://www.geeksforgeeks.org/with-statement-in-python/
  2. https://www.codingem.com/with-statement-in-python/

Implemetasi Kode

Kode 1

class BulletedList:
    def __init__(self):
        self.indent_level = 0

    def __enter__(self):
        self.indent_level += 1
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        self.indent_level -= 1

    def bullet_type(self):
        bullet_types = ["o ", "- ", "* "]
        return bullet_types[self.indent_level % 3]

    def item(self, text):
        print("  " * self.indent_level + self.bullet_type() + text)

with BulletedList() as bp:
    bp.item("Dessert")
    with bp:
        bp.item("Apple Pie")
        with bp:
            bp.item("Apples")
            bp.item("Cinamon")
            bp.item("Sugar")
            bp.item("Flour")
            bp.item("Eggs")
    with bp:
        bp.item("Hot Chocolate")
        with bp:
            bp.item("Milk")
            bp.item("Chocolate powder")
            bp.item("Cream")

Hasil :

  - Dessert
    * Apple Pie
      o Apples
      o Cinamon
      o Sugar
      o Flour
      o Eggs
    * Hot Chocolate
      o Milk
      o Chocolate powder
      o Cream

Kode 2 : Traversing Directories

import os

with os.scandir(".") as entries:
    for entry in entries:
        print(entry.name, "->", entry.stat().st_size, "bytes")

hasil

Documents -> 4096 bytes
Videos -> 12288 bytes
Desktop -> 4096 bytes
DevSpace -> 4096 bytes
.profile -> 807 bytes
Templates -> 4096 bytes
Pictures -> 12288 bytes
Public -> 4096 bytes
Downloads -> 4096 bytes

Kode 3 : Performing High-Precision Calculations

>>> from decimal import Decimal, localcontext

>>> with localcontext() as ctx:
...     ctx.prec = 42
...     Decimal("1") / Decimal("42")
...
Decimal('0.0238095238095238095238095238095238095238095')

>>> Decimal("1") / Decimal("42")
Decimal('0.02380952380952380952380952381')
  1. https://realpython.com/python-with-statement/
  2. https://preshing.com/20110920/the-python-with-statement-by-example/

Link

⚠️ **GitHub.com Fallback** ⚠️