python with语句的原理与用法详解语句的原理与用法详解
本文实例讲述了python with语句的原理与用法。分享给大家供大家参考,具体如下:
之前看到一篇博客说博主python面试时遇到面试官提问with的原理,而那位博主的博文没有提及with原理,故有此文。
关于关于with语句,官方文档中是这样描述的:语句,官方文档中是这样描述的:
The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With
Statement Context Managers). This allows common try…except…finally usage patterns to be encapsulated for convenient
reuse.
with_stmt ::= “with” with_item (“,” with_item)* “:” suite
with_item ::= expression [“as” target]
The execution of the with statement with one “item” proceeds as follows:
The context expression (the expression given in the with_item) is evaluated to obtain a context manager.
The context manager’s __exit__() is loaded for later use.
The context manager’s __enter__() method is invoked.
If a target was included in the with statement, the return value from __enter__() is assigned to it.
Note
The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called.
Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the
suite would be. See step 6 below.
The suite is executed.
The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and
traceback are passed as arguments to __exit__(). Otherwise, three None arguments are supplied.
谷歌翻译成中文就是:谷歌翻译成中文就是:
with语句用于使用由上下文管理器定义的方法来封装块的执行(请参见使用语句上下文管理器一节)。 这允许通用的try…
except…finally使用模式被封装以便于重用【这句话大概意思就是“with语句”类似于try…except…finally封装之后的的情况】。
带有一个“项目”的with语句的执行过程如下:
1.上下文表达式(在with_item中给出的表达式)被评估以获得上下文管理器。【会区分类型来处理,如文件,进程等都可以
使用with语句】
2.上下文管理器的__exit __()被加载供以后使用。【负责上下文的退出】
3.上下文管理器的__enter __()方法被调用。【负责上下文的进入】
4.如果在with语句中包含目标,则将__enter __()的返回值分配给它。【如果with后面跟着as 对象(如with open() as f),那
么此对象获得with上下文对象的__enter__()的返回值,(附:应该是类似操作数据库时的连接对象和游标的区别)】
注意
with语句保证,如果__enter __()方法返回时没有错误,那么将始终调用__exit __()。 因此,如果在分配给目
标列表期间发生错误,它将被视为与套件内发生的错误相同。 请参阅下面的第6步。
5.该套件已执行。【意思就是语句体中的过程执行完毕,执行完毕就到第六步–调用__exit__()来退出】
6.上下文管理器的__exit __()方法被调用。 如果异常导致套件退出,则其类型,值和回溯作为参数传递给__exit __()。
否则,将提供三个无参数。
关于退出返回值:
If the suite was exited due to an exception, and the return value from the __exit__() method was false, the
exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the
statement following the with statement.
If the suite was exited for any reason other than an exception, the return value from __exit__() is ignored, and
execution proceeds at the normal location for the kind of exit that was taken.
中文:
如果套件由于异常而退出,并且__exit __()方法的返回值为false,则会重新对异常进行重新评估。 如果返回值
为true,则异常被抑制,并继续执行with语句后面的语句。