python_with as

本文详细解释了Python中with语句的工作原理及其应用场景,通过示例展示了如何利用with语句简化资源管理和异常处理过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

With语句是什么?
有一些任务,可能事先需要设置,事后做清理工作。对于这种场景,Python的with语句提供了一种非常方便的处理方式。一个很好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。
如果不用with语句,代码如下:

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

这里有两个问题。一是可能忘记关闭文件句柄;二是文件读取数据发生异常,没有进行任何处理。下面是处理异常的加强版本:

file = open("/tmp/foo.txt")
try:
    data = file.read()
finally:
    file.close()

虽然这段代码运行良好,但是太冗长了。这时候就是with一展身手的时候了。除了有更优雅的语法,with还可以很好的处理上下文环境产生的异常。下面是with版本的代码:

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

with如何工作?

这看起来充满魔法,但不仅仅是魔法,Python对with的处理还很聪明。基本思想是with所求值的对象必须有一个enter()方法,一个exit()方法。

紧跟with后面的语句被求值后,返回对象的enter()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的exit()方法。

下面例子可以具体说明with如何工作:

#!/usr/bin/env python
# with_example01.py

class 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
运行代码,输出如下
In __enter__()
sample: Foo
In __exit__()

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

#!/usr/bin/env python
# with_example02.py

class 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 + 10

with 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 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <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/0
ZeroDivisionError: integer division or modulo by zero

实际上,在with后面的代码块抛出任何异常时,exit()方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给exit()方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在exit方法当中。
因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。

python中with可以明显改进代码友好度,比如:

[python] view plain copy

with open('a.txt') as f:  
    print f.readlines()  

为了我们自己的类也可以使用with, 只要给这个类增加两个函数enter, exit即可:
[python] view plain copy

>>> class A:  
    def __enter__(self):  
        print 'in enter'  
    def __exit__(self, e_t, e_v, t_b):  
        print 'in exit'  

>>> with A() as a:  
    print 'in with'  

in enter  
in with  
in exit  

另外python库中还有一个模块contextlib,使你不用构造含有enter, exit的类就可以使用with:
[python] view plain copy

>>> from contextlib import contextmanager  
>>> from __future__ import with_statement  
>>> @contextmanager  
... def context():  
...     print 'entering the zone'  
...     try:  
...         yield  
...     except Exception, e:  
...         print 'with an error %s'%e  
...         raise e  
...     else:  
...         print 'with no error'  
...  
>>> with context():  
...     print '----in context call------'  
...  
entering the zone  
----in context call------  
with no error  

使用的最多的就是这个contextmanager, 另外还有一个closing 用处不大
[python] view plain copy

from contextlib import closing  
import urllib  

with closing(urllib.urlopen('http://www.python.org')) as page:  
    for line in page:  
        print line  
### Python `with as` 语句使用说明 #### 上下文管理器简介 在Python中,`with...as...`被称为上下文管理器,该结构能够简化资源管理过程,确保资源得到及时有效的分配与释放[^1]。 #### 基本语法形式 基本的`with...as...`语句遵循如下模式: ```python with expression [as target]: block_of_code ``` 当执行到此语句时,会先计算expression表达式的值,并将其赋给target变量(如果存在)。随后进入代码块内部运行指定逻辑;一旦完成或遇到异常,则自动触发清理操作[^2]。 #### 文件处理实例 对于文件读取而言,可以利用`with...as...`来安全高效地访问文件内容而不必担心忘记关闭文件流的问题。 ```python with open("example.txt", "r") as file_object: content = file_object.read() print(content) ``` 这段代码展示了如何打开名为`example.txt`的文本文件进行只读(`"r"`), 并把其中的内容存储于字符串content之中。由于采用了`with...as...`, 即使后续发生错误也能保证文件会被正确关闭[^4]。 #### 自定义上下文管理器 除了内置的支持外,还可以创建自定义类以兼容这种机制。只需让此类提供两个特殊方法:`__enter__()`,`__exit__()`即可。 ```python class CustomContextManager: def __init__(self): print("__init__ 被调用") def __enter__(self): print("__enter__ 被调用") return "返回的数据" def __exit__(self, exc_type, exc_val, exc_tb): print("__exit__ 被调用") print(f"{exc_type}, {exc_val}, {exc_tb}") # 返回True表示忽略发生的任何异常 return True with CustomContextManager() as custom_obj: print(custom_obj) try: with CustomContextManager(): raise ValueError("测试异常情况下的行为.") except Exception as e: pass # 此处不会捕获到异常因为__exit__已经处理过了. finally: print('程序正常结束') ``` 上述示例中的CustomContextManager实现了上下文管理协议所需的接口,因此可以在`with...as...`环境中正常使用。即使抛出了未预期的异常,整个应用程序仍然能保持稳定运行状态[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值