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的更多相关文章

  1. Python之 context manager

    在context manager中,必须要介绍两个概念: with as... , 和 enter , exit. 下文将先介绍with语句,然后介绍 __enter__和exit, 最后介绍cont ...

  2. Python——with语句、context manager类型和contextlib库

    目录 一.with语句 二.上下文管理器 三.contextlib模块 基本概念 上下文管理协议(Context Management Protocol) 包含方法 __enter__() 和 __e ...

  3. Python Study(02)之 Context Manager

    上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围.一旦对象进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存).它 ...

  4. Python上下文管理器(context manager)

    上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围.一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存).它的语 ...

  5. pythonic context manager知多少

    Context Managers 是我最喜欢的 python feature 之一,在恰当的时机使用 context manager 使代码更加简洁.清晰,更加安全,复用性更好,更加 pythonic ...

  6. Android的Context Manager(服务管理器)源码剖析-android学习之旅(99)

    Context Manager介绍 Context Manager对应的进程是servicemanager进程,它先于Service Server和服务客户端运行,进入接收IPC数据的待机状态,处理来 ...

  7. Python - Context Manager 上下文管理器

    什么是上下文管理器 官方解释... 上下文管理器是一个对象 它定义了在执行 with 语句时要建立的运行时上下文 上下文管理器处理进入和退出所需的运行时上下文以执行代码块 上下文管理器通常使用 wit ...

  8. Appium+python自动化9-SDK Manager

    前言 SDK Manager到有哪些东西是必须安装的呢? 一.SDK Manager 1.双击打开SDK Manager界面

  9. 第一个 Python 程序 - Email Manager Demo

    看了一些基础的 Python 新手教程后,深深感觉到 Python 的简洁与强大,这是我的第一个 Python Demo.下面是完整代码与执行截图. 代码: # encoding: utf-8 ''' ...

  10. 六、python中context.get()方法

    例:context.get('variant',False) 意思是如果context中不包括variant 就返回False.

随机推荐

  1. 解决NetBeans编辑器中文乱码问题

    在JDK→JRE→lib目录下找到fontconfig.properties.src文件,打开,找到# Component Font Mappings,表示字体映射,可以看到下面列出了几种字体映射集合 ...

  2. java 平台 权限管理

    最近在做公司内部的物流业务平台的权限管理,感触颇多.记录一下 权限管理分两部分:数据权限和操作权限. 数据权限: 这个是和用户相关的. 因为平台是多机构的,所以再考虑数据权限的时候,是按照机构来管理的 ...

  3. Python: 字典的基本操作

    字典是Python里唯一的映射类型.字典是可变的.无序的.大小可变的键值映射,有时候也称为散列表或关联数组. 例子在下面: dic = {"apple":2, "oran ...

  4. 【232】◀▶ IDL显示地理图像

    参考: 01   IMAGE 将图像数据以图形窗体的形式显示. 02   COLORBAR 在已经存在的IDL图形中增加一个colorbar或创建. 03   MAPGRID 在已经存在的IDL地图图 ...

  5. sass揭秘之@mixin,%,@function

    因为文章内含有很多sass代码,如需自己动手查看编译结果,推荐使用sassmeister这款在线编译工具,方便你阅读学习. 在阅读本文章之前,请先确认你已经阅读了上篇文章sass揭秘之变量,不然会给你 ...

  6. Winform 获取当前单击的控件名称 和 向窗体添加控件

    Winform如何获取当前单击的控件名称,比如有100个Button 和一个button_Click()的按钮事件 ,分别点击不同按钮后显示所点击的按钮名称?private void button_C ...

  7. html信息提示框

    1.span <span title="提示信息" data-container="body" data-toggle="inf" d ...

  8. apk添加系统签名

    上一节,可以通过添加su的方式获取系统权限,但这种存在安全隐患,故不推荐,本文通过获取数字签名方式获取系统权限. 在我们的AndroidManifest.xml中添加    android:share ...

  9. Acadia Lab 6 轮盘游戏机

    WRTnode 肯定不是亲生的... 果断转投Acadia —.— 不是国军不给力,奈何共军有高达 为啥不转树莓派?因为选做实验肯定有很多人用树莓派做...我抢不过他们,只能挑点冷门的蹭分_(:з」 ...

  10. HP工控机 G9 安装系统需注意

    HP工控机 G9 装系统需要:简单唠叨几句 1.F10 进配置,选择设置图标-选择存储图标-选择阵列卡图标-根据中间框提示制作riad(必须) 2.加载驱动 驱动直接复制到U盘根目录下,选择F11选择 ...