Python __enter__() Magic Method

4/5 - (1 vote)

πŸ’‘ 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('') as finxter:
    # Called finxter.__enter__()
    # 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 class MySecretConnection a context manager, i.e., allowing it to be used in a with statement.
  • You create a with statement, assigning a specific instance of MySecretConnection — that connects to our Python puzzle app '' — to the variable finxter.

The following output shows that the respective magic methods are called when entering and leaving the with statement on our MySecretConnection instance:


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.