Table of Contents
1. What is the With statement?
2. How does with work?
3. Related terms
Home Backend Development Python Tutorial About the usage of with in python

About the usage of with in python

Apr 09, 2018 am 11:43 AM
python with usage

This article shares with you the usage of with in python. Friends in need can refer to it


1. What is the With statement?


There are some tasks that may need to be set up in advance and cleaned up afterwards. For this scenario, Python's with statement provides a very convenient way to deal with it. A good example is file handling, where you need to get a file handle, read data from the file, and then close the file handle.

If you do not use the with statement, the code is as follows:

file = open("/tmp/foo.txt")
data = file.read()file.close()
Copy after login

There are two problems here:

One is that you may forget to close the file handle;
The second is to read data from the file An exception occurred and no handling was performed.

The following is an enhanced version of exception handling:

try:
    f = open('xxx')except:
    print 'fail to open'
    exit(-1)try:    do somethingexcept:    do somethingfinally:
     f.close()
Copy after login

Although this code runs well, it is too verbose.

This is the time for with to show off his skills. In addition to having more elegant syntax, with can also handle exceptions generated by the context very well.

The following is the code for the with version:

with open("/tmp/foo.txt") as file:
    data = file.read()
Copy after login

2. How does with work?

After the statement immediately following with is evaluated, the __enter__() of the object is returned. The method is called, and the return value of this method will be assigned to the variable after as.
When all the code blocks following with are executed, the __exit__() method of the previously returned object will be called.

The following example can specifically illustrate how with works:

#!/usr/bin/env python# with_example01.pyclass Sample:
    def __enter__(self):
        print "In __enter__()"
        return "Foo"
    def __exit__(self, type, value, trace):
        print "In __exit__()"def get_sample():
    return Sample()with get_sample() as sample:    print "sample:", sample
Copy after login

Run the code, the output is as follows

bash-3.2$ ./with_example01.pyIn __enter__()sample: FooIn __exit__()
Copy after login

正如你看到的: 1. __enter__()方法被执行 2. __enter__()方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’ 3. 执行代码块,打印变量”sample”的值为 “Foo” 4. __exit__()方法被调用
with真正强大之处是它可以处理异常。可能你已经注意到Sample类的 __exit__ 方法有三个参数 val, type 和 trace。 这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。

#!/usr/bin/env python# with_example02.pyclass Sample:
    def __enter__(self):
        return self    def __exit__(self, type, value, trace):
        print "type:", type        print "value:", value        print "trace:", trace    def do_something(self):
        bar = 1/0
        return bar + 10with Sample() as sample:
    sample.do_something()
Copy after login

这个例子中,with后面的get_sample()变成了Sample()。这没有任何关系,只要紧跟with后面的语句所返回的对象有 __enter__() 和 __exit__() 方法即可。此例中,Sample()的 __enter__() 方法返回新创建的Sample对象,并赋值给变量sample。

代码执行后:

bash-3.2$ ./with_example02.py
type: <type &#39;exceptions.ZeropisionError&#39;>value: integer pision or modulo by zerotrace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
  File "./with_example02.py", line 19, in <module>
    sample.do_something()
  File "./with_example02.py", line 15, in do_something
    bar = 1/0ZeropisionError: integer pision or modulo by zero
Copy after login

实际上,在with后面的代码块抛出任何异常时,__exit__() 方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给 __exit__() 方法,因此抛出的ZeropisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在 __exit__ 方法当中。

另外,__exit__ 除了用于tear things down,还可以进行异常的监控和处理,注意后几个参数。要跳过一个异常,只需要返回该函数True即可。

下面的样例代码跳过了所有的TypeError,而让其他异常正常抛出。

def __exit__(self, type, value, traceback):
    return isinstance(value, TypeError)
Copy after login

上文说了 __exit__ 函数可以进行部分异常的处理,如果我们不在这个函数中处理异常,他会正常抛出,这时候我们可以这样写(python 2.7及以上版本,之前的版本参考使用contextlib.nested这个库函数):

try:    with open( "a.txt" ) as f :        do something
except xxxError:    do something about exception
Copy after login

总之,with-as表达式极大的简化了每次写finally的工作,这对保持代码的优雅性是有极大帮助的。

如果有多个项,我们可以这么写:

with open("x.txt") as f1, open(&#39;xxx.txt&#39;) as f2:    do something with f1,f2
Copy after login

因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。

To use the with statement, you must first understand the concept of context manager. With a context manager, the with statement can work.
The following is a set of concepts related to context managers and with statements.
Context Management Protocol: Contains methods __enter__() and __exit__(). Objects that support this protocol must implement these two methods.
Context Manager: An object that supports the context management protocol. This object implements the __enter__() and __exit__() methods. The context manager defines the runtime context to be established when executing the with statement, and is responsible for executing the entry and exit operations in the context of the with statement block. A context manager is usually called using the with statement, but can also be used by calling its methods directly.
Runtime context (runtime context): Created by the context manager, implemented through the __enter__() and __exit__() methods of the context manager. The __enter__() method enters the runtime context before the statement body is executed. __exit__( ) exits from the runtime context after the statement body is executed. The with statement supports the concept of runtime context.
Context Expression: The expression following the keyword with in the with statement, which returns a context manager object.
Statement body (with-body): The code block wrapped in the with statement will call the context manager's __enter__() method before executing the statement body, and the __exit__() method will be executed after the statement body is executed.

Related links:
1.http://blog.kissdata.com/2014/05/23/python-with.html
2.https://www.ibm .com/developerworks/cn/opensource/os-cn-pythonwith/

Related recommendations:

How to understand the with statement in Python

Detailed explanation of the use of focus-within


The above is the detailed content of About the usage of with in python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles