Python.with.context-manager
Context Manager
1. Context Manager简介
"Context managers are a way of allocating and releasing some sort of resource exactly where you need it." Ref[4]
例如:
with file("/tmp/foo", "w") as foo:
print >> foo, "Hello!"
Context Manager是随with一起引入的。
"A context manager is an object that defines the runtime context to be established when executing a with statement.
The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the
block of code." Ref[11]
"Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking
resources, closing opened files, etc." Ref[11]
2. 创建Context Manager
2.1 Context Manager Type
with and context manager
"Python’s with statement supports the concept of a runtime context defined by a context manager. This is implemented
using two separate methods that allow user-defined classes to define a runtime context that is entered before the statement body
is executed and exited when the statement ends. " Ref[6]
context management protocol
"The context management protocol consists of a pair of methods that need to be provided for a context manager
object to define a runtime context:" Ref[6]
contextmanager.__enter__() contextmanager.__exit__(exc_type, exc_val, exc_tb)
contextlib
"Python’s generators and the contextlib.contextmanager decorator provide a convenient way to implement these protocols.
If a generator function is decorated with the contextlib.contextmanager decorator, it will return a context manager
implementing the necessary __enter__() and __exit__() methods, rather than the iterator produced by an
undecorated generator function." Ref[6]
2.2 使用contextlib模块
"the simplest way is using the contextmanager decorator from the contextlib library, and invoking yield in your context manager
function in between the setup and teardown steps." Ref[4]
Ref[4] 中的例子:
import contextlib
import time @contextlib.contextmanager
def time_print(task_name):
t = time.time()
try:
yield
finally:
print task_name, "took", time.time() - t, "seconds." with time_print("processes"):
[doproc() for _ in range(500)] # processes took 15.236166954 seconds. with time_print("threads"):
[dothread() for _ in range(500)] # threads took 0.11357998848 seconds.
Reference
1. contextlib — Utilities for with-statement contexts
https://docs.python.org/2/library/contextlib.html
2. With Statement Context Managers
https://docs.python.org/2/reference/datamodel.html#context-managers
3. with statement
https://docs.python.org/2/reference/compound_stmts.html#with
4. Introduction to Context Managers in Python (Read Again)
http://eigenhombre.com/2013/04/20/introduction-to-context-managers/
5. Fixture functions using “yield” / context manager integration
https://pytest.org/latest/yieldfixture.html
6. Build-in Types (To Read)
https://docs.python.org/2/library/stdtypes.html#typecontextmanager
7. PEP 343 -- The "with" Statement (To Read)
https://www.python.org/dev/peps/pep-0343/
8. Coding with context managers
http://python3porting.com/improving.html
9. Python: Tips, Tricks and Idioms - Part 2 - Decorators and Context Managers
https://codefisher.org/catch/blog/2015/02/10/python-decorators-and-context-managers/
10. Defining Context Managers the Easy Way
https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch09s22.html
11. With Statement Context Managers
https://docs.python.org/2/reference/datamodel.html#context-managers
Todo:
http://www.rafekettler.com/magicmethods.html
Python.with.context-manager的更多相关文章
- Python之 context manager
在context manager中,必须要介绍两个概念: with as... , 和 enter , exit. 下文将先介绍with语句,然后介绍 __enter__和exit, 最后介绍cont ...
- Python——with语句、context manager类型和contextlib库
目录 一.with语句 二.上下文管理器 三.contextlib模块 基本概念 上下文管理协议(Context Management Protocol) 包含方法 __enter__() 和 __e ...
- Python Study(02)之 Context Manager
上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围.一旦对象进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存).它 ...
- Python上下文管理器(context manager)
上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围.一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存).它的语 ...
- pythonic context manager知多少
Context Managers 是我最喜欢的 python feature 之一,在恰当的时机使用 context manager 使代码更加简洁.清晰,更加安全,复用性更好,更加 pythonic ...
- Android的Context Manager(服务管理器)源码剖析-android学习之旅(99)
Context Manager介绍 Context Manager对应的进程是servicemanager进程,它先于Service Server和服务客户端运行,进入接收IPC数据的待机状态,处理来 ...
- Python - Context Manager 上下文管理器
什么是上下文管理器 官方解释... 上下文管理器是一个对象 它定义了在执行 with 语句时要建立的运行时上下文 上下文管理器处理进入和退出所需的运行时上下文以执行代码块 上下文管理器通常使用 wit ...
- Appium+python自动化9-SDK Manager
前言 SDK Manager到有哪些东西是必须安装的呢? 一.SDK Manager 1.双击打开SDK Manager界面
- 第一个 Python 程序 - Email Manager Demo
看了一些基础的 Python 新手教程后,深深感觉到 Python 的简洁与强大,这是我的第一个 Python Demo.下面是完整代码与执行截图. 代码: # encoding: utf-8 ''' ...
- 六、python中context.get()方法
例:context.get('variant',False) 意思是如果context中不包括variant 就返回False.
随机推荐
- oracle中字符串连接用||
oracle中字符串连接用|| create or replace procedure testIf(idid number) is v_name stu.name%type; v_age stu.a ...
- bcm cmd
BCM.1> port ge en=0 ;Disable all GbEBCM.1> tx 2 pbm=ge2,fe7 ;Transmit 2 packets out of both po ...
- STL迭代器之一:偏特化
在stl的算法中运用容器的迭代器时,很可能经常会用到迭代器相应型别(例如迭代器所指物的型别),假设算法中有必要声明一个变量,以"迭代器所指对象的型别"为类型,如何是好,例如我们写一 ...
- DICOM图像像素值(灰度值)转换为CT值
CT值的单位是Hounsfield,简称为Hu,范围是-1024-3071.用于衡量人体组织对X射线的吸收率,设定水的吸收率为0Hu. 在DICOM图像读取的过程中,我们会发现图像的像素值有可能不是这 ...
- SE要有政治能力
不光是SE,任何人都需要政治能力. 那么,什么是政治能力?政治能力就是让周围的人跟你一起,一条心,完成你想干的事情的能力. 我们任何人,生活也好,工作也好,学习也好,都不是一个人孤单进行的,都是通过几 ...
- FireDac 的RecordCount 相关测试 记录。
unit Unit4; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System ...
- asp.net core获取HttpContext相关操作
建立类: using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;us ...
- openssl使用多种方法签名、自签名
1.自建CA 自建CA的机制:1.生成私钥2.创建证书请求,在创建证书请求过程中由于需要提供公钥,而公钥来源于私钥,所以也需要指定私钥来创建证书请求,而实际上这里提供私钥的作用就是提取其中的公钥,这一 ...
- Centos安装jdk
运行Java应用的时候,提示无法找到JAVA_HOME,查询java -version [jifeng@localhost bin]$ java -version java version " ...
- nagios二次开发(四)---nagios监控原理和nagios架构简介
nagios监控原理 下面根据上面摘自网络的原理图对nagios的监控原理进行一下简单的说明: 1.nagios通过nsca进行被动监控.那么什么是被动监控呢?被动监测:就是指由被监测的服务器主动上传 ...