2

I learnt recently the 'with' statement in python and its usage, mainly from the article Understanding Python's "with" statement and the official documentation for with statement.

The most used example is understandable for me

with open("x.txt") as f:
    data = f.read()
    do something with data

ok so we open the file x.txt, we perform some tasks with it and it is automatically closed. The f variable is used to read in the file and do other tasks.

But in the official documentation, the target variable after the expression is optional:

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

I didn't find any example of with statement used without a target variable. Is there cases where this variable is not necessary?

Antwane
  • 20,760
  • 7
  • 51
  • 84
  • multiprocessing.Lock is an example http://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessing – Padraic Cunningham Feb 26 '15 at 16:03
  • Anecdote: I once wrote a `with silenced_output():` statement, which redirected all `stdout` messages to dev/null. `with silenced_output() as x:` wouldn't make much sense, because I didn't need to do anything with x. – Kevin Feb 26 '15 at 16:03
  • See also [`contextlib.suppress`](https://docs.python.org/3/library/contextlib.html#contextlib.suppress). – jonrsharpe Feb 26 '15 at 16:04
  • Ok, I didn't noticed that this question have already been answerd [here](http://stackoverflow.com/a/26342829/1887976). Sorry about that – Antwane Feb 26 '15 at 16:13

2 Answers2

2
from threading import Lock

lock = Lock()

with lock:
    # access critical data

# continue

hope it helps.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41
2

Yes there are, you can find a couple of them in this answer : What is the python "with" statement designed for?

The most straightforward I can think of is the thread lock (also listed in the previous link):

lock = threading.Lock()
with lock:
    # Critical section of code

For the record I'd also quote the with doc :

The with statement is used to wrap the execution of a block with methods [...]. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

As you don't always need a variable in try...except...finally, you do not absolutely need a target variable in a with statement.

Community
  • 1
  • 1
d6bels
  • 1,432
  • 2
  • 18
  • 30