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?