How to use "with" statements other than file I/O

Asked 2 years ago, Updated 2 years ago, 20 views

I often see Python with statements about file I/O, but is there any other way to use them?Other than with open('myfile')asf:, do you see any examples of using or using the with statement?

python

2022-09-30 19:33

7 Answers

If you don't do post-processing, I think it's okay as long as there are resources left.
It feels like I've checked Python 2.7's standard attached library.

  • Handling the start and end of the unit test library (unittest)
  • Handling process management and interprocess communication synchronization (multiprocessing)

It seems to be used in .In fact, if __enter__ and _exit__ are declared, they can be used in user-defined objects, so I personally think it's good to use them more and more.


2022-09-30 19:33

As Mattn's already mentioned, it is convenient if post-processing is required.

Implementations such as:

cwd=os.getcwd()
os.chdir('/tmp/foo')
try:
    run()#something
finally:
    os.chdir(cwd)

Implement the following cd for use with :

@contextlib.contextmanager
def cd(target_dir):
    cwd=os.getcwd()
    try:
        os.chdir(target_dir)
        yield
    finally:
        os.chdir(cwd)

You can use it as follows:

with cd('/tmp/foo'):
    run()#something

There are several examples of using with in Fabric http://docs.fabfile.org/en/latest/tutorial.html


2022-09-30 19:33

threading.Lock almost always uses with:

class Foo(object):
  def__init__(self):
    self.lock=threading.Lock()

  def Bar (self):
    with self.lock:
      # atomic operation

It's not that with is convenient to use, but it's a case where with should be used.


2022-09-30 19:33

Non-pastered ones are also common in the context of DB transactions.

import sqlite3

con=sqlite3.connect(":memory:")
con.execute("create table person(id integer primary key, firstname varchar unique)"")

# Successful, con.commit() is called automatically afterwards
with con:
    con.execute("insert into person(firstname) values(?), ("Joe",))

# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be caught

http://docs.python.jp/2.7/library/sqlite3.html#id11


2022-09-30 19:33

Python 3 also often uses patches for newly packaged mock modules.

http://docs.python.jp/3/library/unittest.mock.html#quick-guide

If you don't return the mock answer, it will affect other tests, so you should use with.


2022-09-30 19:33

Other than the past papers, I will also use pytest.

import pytest

def test_zero_division():
    with pytest.rises (ZeroDivisionError):
        1 / 0

Note: Assertions about expected exceptions


2022-09-30 19:33

It is also used to limit the scope of asynchronous processing in trio.


2022-09-30 19:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.