search
HomeBackend DevelopmentPython TutorialAbout the usage of with in python

About the usage of with in python

Apr 09, 2018 am 11:43 AM
pythonwithusage

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()

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()

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()

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

Run the code, the output is as follows

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

正如你看到的: 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()

这个例子中,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

实际上,在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)

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

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

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

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

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

因此,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
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool