💡 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
__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
__exit__()magic methods to make your class
MySecretConnectiona context manager, i.e., allowing it to be used in a
- You create a
withstatement, assigning a specific instance of
MySecretConnection— that connects to our Python puzzle app
'https://finxter.com'— to the variable
The following output shows that the respective magic methods are called when entering and leaving the
with statement on our
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.