Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 859583
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T08:41:56+00:00 2026-05-15T08:41:56+00:00

I came across the Python with statement for the first time today. I’ve been

  • 0

I came across the Python with statement for the first time today. I’ve been using Python lightly for several months and didn’t even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:

  1. What is the Python with statement
    designed to be used for?
  2. What do
    you use it for?
  3. Are there any
    gotchas I need to be aware of, or
    common anti-patterns associated with
    its use? Any cases where it is better use try..finally than with?
  4. Why isn’t it used more widely?
  5. Which standard library classes are compatible with it?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T08:41:57+00:00Added an answer on May 15, 2026 at 8:41 am
    1. I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. More details can be found in PEP 343. For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow. The with statement can thus be used in ways similar to the RAII pattern in C++: some resource is acquired by the with statement and released when you leave the with context.

    2. Some examples are: opening files using with open(filename) as fp:, acquiring locks using with lock: (where lock is an instance of threading.Lock). You can also construct your own context managers using the contextmanager decorator from contextlib. For instance, I often use this when I have to change the current directory temporarily and then return to where I was:

      from contextlib import contextmanager
      import os
      
      @contextmanager
      def working_directory(path):
          current_dir = os.getcwd()
          os.chdir(path)
          try:
              yield
          finally:
              os.chdir(current_dir)
      
      with working_directory("data/stuff"):
          # do something within data/stuff
      # here I am back again in the original working directory
      

      Here’s another example that temporarily redirects sys.stdin, sys.stdout and sys.stderr to some other file handle and restores them later:

      from contextlib import contextmanager
      import sys
      
      @contextmanager
      def redirected(**kwds):
          stream_names = ["stdin", "stdout", "stderr"]
          old_streams = {}
          try:
              for sname in stream_names:
                  stream = kwds.get(sname, None)
                  if stream is not None and stream != getattr(sys, sname):
                      old_streams[sname] = getattr(sys, sname)
                      setattr(sys, sname, stream)
              yield
          finally:
              for sname, stream in old_streams.iteritems():
                  setattr(sys, sname, stream)
      
      with redirected(stdout=open("/tmp/log.txt", "w")):
           # these print statements will go to /tmp/log.txt
           print "Test entry 1"
           print "Test entry 2"
      # back to the normal stdout
      print "Back to normal stdout again"
      

      And finally, another example that creates a temporary folder and cleans it up when leaving the context:

      from tempfile import mkdtemp
      from shutil import rmtree
      
      @contextmanager
      def temporary_dir(*args, **kwds):
          name = mkdtemp(*args, **kwds)
          try:
              yield name
          finally:
              shutil.rmtree(name)
      
      with temporary_dir() as dirname:
          # do whatever you want
      
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 440k
  • Answers 440k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Yes, You can fully control the $vars['template_files'] array. I always… May 15, 2026 at 5:22 pm
  • Editorial Team
    Editorial Team added an answer A background ping using an IFrame is performed, and if… May 15, 2026 at 5:22 pm
  • Editorial Team
    Editorial Team added an answer Well for /r ...\data %%x in (*.png) do pngcrush "%%x"… May 15, 2026 at 5:22 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.