__aenter__ — Intermediate Playground
Async version of __enter__ for async with blocks
Python Playground
# Real-world __aenter__ usage
class Money:
def __init__(self, amount, currency="USD"):
self.amount = amount
self.currency = currency
def __repr__(self):
return f"Money({self.amount}, '{self.currency}')"
def __str__(self):
symbols = {"USD": "$", "EUR": "€", "GBP": "£"}
sym = symbols.get(self.currency, self.currency)
return f"{sym}{self.amount:.2f}"
def __add__(self, other):
if self.currency != other.currency:
raise ValueError(f"Cannot add {self.currency} and {other.currency}")
return Money(self.amount + other.amount, self.currency)
def __eq__(self, other):
return self.amount == other.amount and self.currency == other.currency
def __lt__(self, other):
if self.currency != other.currency:
raise ValueError("Cannot compare different currencies")
return self.amount < other.amount
def __bool__(self):
return self.amount != 0
a = Money(10.50)
b = Money(5.25)
print(f"{a} + {b} = {a + b}")
print(f"Equal: {a == b}")
print(f"Less than: {b < a}")
print(f"Has value: {bool(a)}")
Output
Click "Run" to execute your code
__aenter__ enables your classes to integrate seamlessly with Python's operators and built-in functions.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?