__enter__
Dunder MethodPython 2.0+Intermediate
Called at the start of a with block; returns the context resource
Quick Info
- Documentation
- Official Docs
- Python Version
- 2.0+
Learn by Difficulty
Quick Example
python
class Timer: def __enter__(self): import time self.start = time.time() print("Timer started") return self def __exit__(self, *args): import time elapsed = time.time() - self.start print(f"Elapsed: {elapsed:.4f}s") with Timer(): total = sum(range(1000000)) print(f"Sum: {total}")
__enter__ called at the start of a with block; returns the context resource. Implementing it lets you customize how Python interacts with your objects.
Try in PlaygroundTags
oopmagic-methodprotocolcore