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]

例如: 

1 with file("/tmp/foo", "w") as foo:
2     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]

1 contextmanager.__enter__()
2 
3 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] 中的例子:

 1 import contextlib
 2 import time
 3 
 4 @contextlib.contextmanager
 5 def time_print(task_name):
 6     t = time.time()
 7     try:
 8         yield
 9     finally:
10         print task_name, "took", time.time() - t, "seconds."
11 
12 with time_print("processes"):
13     [doproc() for _ in range(500)]
14 
15 # processes took 15.236166954 seconds.
16 
17 with time_print("threads"):
18     [dothread() for _ in range(500)]
19 
20 # 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

转载于:https://www.cnblogs.com/cwgk/p/5096741.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/543318.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

micropython移植教程_【教程】智能编程T-Watch手表初试micropython之电子秤教程

原标题:【教程】智能编程T-Watch手表初试micropython之电子秤教程 【项目的故事】 在极客玩具中,我一直喜欢穿戴类和小车类。前后做过两只运动心率表,并且参与过麦步手表的测试。TTGO最新出品了一块叫做T-Watch的手表,实际上&…

音乐和计算机跨界融合,音乐类综艺跨界融合有了新思路

图集8月9日《人民日报》刊文,对原创综艺节目《幻乐之城》匠心做原创的新思路、新经验、新趋势进行了表扬,文章指出:“音乐电影”的节目模式在呈现出音乐与电影双重质感的同时,也为国内音乐类综艺节目的跨界融合发展提供了新的思路…

mysql 下载到其他盘中_MYSQL 如果把数据文件保存到其他磁盘里

今天在CSDN上有人问起分开存储数据文件的问题。现在写下来。为了突破磁盘搜索的瓶颈。我们要把MYSQL的数据和索引保存到其他不同的磁盘中。目前还只是支持MyISAM引擎。在MYSQL中,官这个叫象征性链接。1、在WINDOWS下的象征性链接。数据库目录:E:/LAMP/my…

python定义了函数却显示未定义_python

我正在编写一个脚本,在我的脚本中,我具有以下功能: def insert_image(cursor, object_id, sku): product_obj core.Object.get(object_id) string_sku str(sku) folder string_sku[0] string_sku[1] string_sku[2] found_url False # K…

以下不属于计算机安全术语,基础知识(D).doc

1、计算机硬件是指组成计算机的任何机械的、磁性的、电子的装置或部件,其中微型计算机的主要组成部分有:A.CPU、存储器、基本输入输出设备和其他外围设备B.硬件系统和软件系统C.主机和系统软件D.主机和显示器答案:A (2)2、计算机网络的分类标…

java api项目配置统一的错误返回json提示

2019独角兽企业重金招聘Python工程师标准>>> 项目使用的json解析框架是fastjson自定义的返回对象如下:package com.test;public class ResultObj {private boolean result;private int code200;private String msg;private Object data;private PagerRes…

mysql没多久自动断开服务_mysql 长时间没连接了 就会自动断开服务

这是因为mysql 长时间没连接了 就会自动断开服务。 解决办法 1、首先,下载必须的jar包 dbcp 包,目前版本是1.2.1:http://jakarta.apache.org/commons/ dbcp / pool包,目前版本是1.3:http://jakarta.apache.org/commons…

python将print内容输入txt_Python将矩阵写入txt文件,保持格式

我正在努力把我的代码输出写入一个txt文件,同时保持格式。代码如下:import os # Compute matrix titles [Filename, Date] matrix [titles] for directory, __, files in os.walk(MY_DIRECTORY): # replace with actual directory path for filename i…

浙江大学计算机学院研究生论文盲审,浙江理工大学研究生学位论文盲审实施办法...

浙理工研〔2014〕11号为进一步完善研究生教育质量监控体系,提高研究生培养质量,根据学校实际,特修订本办法。一、工作原则研究生学位论文盲审工作在校硕士和博士学位评定委员会领导下开展,由研究生部(校学位办)和学院组织实施。除…

iOS开发UI篇—使用storyboard创建导航控制器以及控制器的生命周期

一、基本过程 新建一个项目,系统默认的主控制器继承自UIViewController,把主控制器两个文件删掉。 在storyboard中,默认的控制器是View Controller,而我们需要的是导航控制器,那么就把系统的给删掉,拖一个导…

mysql 5.5 1366错误_laravel5.3 在 mysql5.1中运行出错 error: 1366 Incorrect integer

Laravel 在 MySQL5.1 下运行出错 ,错误如下:SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 1 for column status at row 1 (SQL: insert into cases (case_name, status, updated_at, created_at) values (fdsafdsadsa, 1, 1474504956…

python的交互式解释器_python3.4.1解释器python交互式图形编程实例(三)

本文实例为大家分享了python交互式图形编程实例的第三部代码,供大家参考,具体内容如下 #!/usr/bin/env python3 # -*- coding: utf-8 -*- #时钟 from turtle import * from datetime import * def Skip(step): penup() forward(step) pendown() def mkHa…

教师计算机培训心得体会范文,xx年教师计算机培训心得体会范文.doc

《xx年教师计算机培训心得体会范文.doc》由会员分享,提供在线免费全文阅读可下载,此文档格式为doc,更多相关《xx年教师计算机培训心得体会范文.doc》文档请在天天文库搜索。1、 xx年教师计算机培训心得体会范文撰写人&#xff1a…

mysql 5.6 5.7不兼容_同一条sql在mysql5.6和5.7版本遇到的问题。

之前用的是mysql 5.6版本,执行select * from table group by colunm 是可以出结果的,但是切换的5.7版本,这条sql就报错,Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column informat…

计算机组成原理输入实验报告,计算机组成原理实验报告

/串形式构成的 8 位字长的运算器。右方为低 4 位运算芯片,左方为高 4 位运算芯片。低位芯片的进位输出端 Cn4 与高位芯片的进位输入端 Cn 相连,使低 4 位运算产生的进位送进高 4位运算中。低位芯片的进位输入端 Cn 可与外来进位相连,高位芯片…

python中导入模块队列_【每日学习】Python中模块的导入

模块的概念:每一个以扩展名py结束的Python源代码文件都是一个模块模块名同样也是一个标识符,需要符合标识符的命名规则在模块中定义的全局变量、函数、类都是提供给外界直接使用的工具模块就好比工具包,要想使用这个工具包中的工具&#xff0…

python从txt读取数据并画图_Python读取txt某几列绘图的方法

晚上帮同学用Python脚本绘图,大概需求是读取一个txt文件的两列分别作为x和y的值,绘图即可,代码如下: #coding:utf-8 import numpy as np import matplotlib.pyplot as plt import pylab ## 绘制该文件中的数据 ## 需要引入pylab库…

计算机组成原理 参考,计算机组成原理参考练习

《计算机组成原理参考练习》由会员分享,可在线阅读,更多相关《计算机组成原理参考练习(6页珍藏版)》请在人人文库网上搜索。1、年级:重庆邮电大学移通学院2013-2014 学年第1 学期 考试专业:计算机科学与技术、网络工程、软件工程 …

2016.04.29-2016.05.05这周工作时间和内容

这周的学习内容:这周我还和平常一样,上了三个小时的课,下课用一个小时来巩固自己的学习的知识,然后对自己学习的内容加以深化,其实我自己对于学习是懒的,懒的学,懒的动,每次上课虽然…

setuptools安装_在Ubuntu 18.04系统上安装ERPNext ERP

简介ERPNext是一个功能丰富的企业级ERP系统,使用Frappe框架编写,一个Python和JavaScript的Web应用程序框架,具有:会计管理、库存管理制造管理、客户关系管理系统、销售管理、采购管理、项目管理等特性。ERPNext ERP系统适用于中小…