object.__enter__(self)π‘ Summary: Python calls the __enter__() magic method when starting a with block whereas the __exit__() method is called at the end. An object that implements both __enter__() and __exit__() methods is called a context manager. By defining those methods, you can create your own context manager.
class MySecretConnection:
def __init__(self, url):
self.url = url
def __enter__(self):
print('entering', self.url)
def __exit__(self, exc_type, exc_val, exc_tb):
print('leaving', self.url)
with MySecretConnection('https://finxter.com') as finxter:
# Called finxter.__enter__()
pass
# Called finxter.__exit__()
- We define a custom class
MySecretConnection. This could hold any connection in your Python script so you can easily scrape a website or do anything you’d like. - You define the
__enter__()and__exit__()magic methods to make your classMySecretConnectiona context manager, i.e., allowing it to be used in awithstatement. - You create a
withstatement, assigning a specific instance ofMySecretConnection— that connects to our Python puzzle app'https://finxter.com'— to the variablefinxter.
The following output shows that the respective magic methods are called when entering and leaving the with statement on our MySecretConnection instance:
entering https://finxter.com leaving https://finxter.com
We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.