Hey everybody. I was reading some code on the website and I saw this:

with open(FILE) as number_file:
lucky_numbers = [set(line.strip().split('-')) for line in number_file]

What does "with ... as ..." mean? What is it used for? How is it used?

The with statement applies to instances having 2 methods: "__enter__" and "__exit__". When the with statement is encountered, the instance's __enter__ method is called and its return value is used for the 'as' part of the statement. When the block exits, the instance's __exit__ method is called to perform cleanup action. In the case of a file object, the __exit__ method closes the file.

class A(object):
    def __enter__(self):
        print("entering block")
        return "block value"
    def __exit__(self, *args):
        print("exiting block")
        
with A() as value:
    print(value)

"""
my output -->
entering block
block value
exiting block
"""

An alternative to writing a class to create such 'context' instances is to write a function with a single "yield" statement and use the contextmanager decorator like this

from contextlib import contextmanager

@contextmanager
def B():
    print("entering block")
    yield "block value"
    print("exiting block")
    
with B() as value:
    print(value)

""" my output -->
entering block
block value
exiting block
"""

As a more useful example, here is a context which executes a block of statement in a given directory and comes back to the initial directory at the end of the block

@contextmanager
def working_directory(path):
    import os
    old = os.getcwd()
    try:
        os.chdir(path)
        yield # this is where the code in the "with" block will be executed
    finally:
        os.chdir(old)

import os.path

with working_directory(os.path.expanduser("~")):
    print(os.getcwd())

Here are 2 more funny contexts: http://www.daniweb.com/software-development/python/code/317854

Thank You!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.