Python 的with关键字
Python 的with关键字
看别人的代码时,with关键字经常会出现,博主决定梳理一下with以及python中上下文(context)的概念
1. 上下文管理器概念
Context Manager指的是python在执行一段代码前后,做的一些预处理和后处理,使得代码块运行处于一个小的环境(surrounding),出了这个小环境之后,资源释放,环境中的各种配置也失效。
例如在打开文件需要关闭,连接数据库后需要关闭连接。很多优雅第三方库也会利用上下文使得对象进入特定的某种状态。
2. with关键字
with的基本用法如下:
with EXPR as VAR:
BLOCK
其中发生了一系列过程:
- EXPR语句被执行,得到ContextManager
- 调用ContextManager.__enter__方法
- 如果有as VAR,则ContextManager.__enter__的返回值赋给VAR,否则就不管返回值
- 执行BLOCK,如果有VAR被用到,就和普通变量一样
- 调用ContextManager.__exit__方法
- __exit__有三个参数:type, value, traceback,BLOCK出异常时会得到对应值,正常情况就都为None
- __exit__返回值为True表示BLOCK中出现的异常可以忽略,False表示需要raise
3. 例子
3.1 资源操作:
class CustomOpen:
def __init__(self, filename: str):
self.__filename = filename
self.__handler = None
def __enter__(self):
print("enter......")
self.__handler = open(self.__filename)
return self.__handler
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit...", exc_type, exc_val, exc_tb)
if self.__handler is not None:
self.__handler.close()
return True
with CustomOpen("hello.txt") as f:
print(f.read())
运行结果:
enter......
hello world
exit... None None None
3.2 状态维护
class CustomBrain:
def __init__(self):
self.__status = "normal"
def say(self):
if self.__status == "normal":
print("You're a great man")
elif self.__status == "special":
print("You are a very outstanding person ")
def __enter__(self):
self.__status = "special"
def __exit__(self, exc_type, exc_val, exc_tb):
self.__status = "normal"
brain = CustomBrain()
brain.say() # 普通状态
# 可以通过上下文维护一些状态
with brain:
brain.say() # 特殊状态
brain.say() # 普通状态
运行结果:
You're a great man
You are a very outstanding person
You're a great man
4. 使用contextlib简化编写
python内置的标准库contextlib可以是的代码书写更加简洁,本质是一样的。比较有用的是contextlib.contextmanager这个装饰器,被装饰的函数在yield的前面相当于__enter__,yield的后面相当于__exit__,yield本身的返回值赋给as后的变量
所以第一个示例可以这么写:
from contextlib import contextmanager
@contextmanager
def custom_open(filename: str):
print("enter......")
handler = open(filename)
yield handler
print("exit...")
handler.close()
with custom_open("hello.txt") as f:
print(f.read())
还是优雅了许多~
Python 的with关键字的更多相关文章
- Python中的关键字的用法
Python有哪些关键字 -Python常用的关键字 and, del, from, not, while, as, elif, global, or, with, assert, else, if, ...
- python的标识符&&关键字
和Java语言一样,python也有标识符和关键字.那么,你是否知道python的关键字呢?一起先从标识符了解python吧. 什么是标识符? 标识符,开发人员在开发过程中自定义的一些符号和名称. 标 ...
- python中super关键字的用法
http://python.jobbole.com/86787/ class A: def __init__(self): print "enter A" print ...
- python正则提取关键字
python使用正则表达式提取关键字 import sys reload(sys) sys.setdefaultencoding("utf-8") import re ss = & ...
- python 位置参数和关键字参数 *args **kwargs
#!/usr/bin/env pythondef foo(*args,**kwargs): print('args: {0}'.format(args)) print('kwargs {0}'.for ...
- python进阶之关键字和运算符触发魔法方法
前言 python有众多的魔法方法,它们会在满足某种条件下触发执行,掌握好魔法方法的使用,可以加快程序的运行效率,同时减少逻辑调用. 关键字与魔法方法 python的一些魔法方法是关键字触发的,即py ...
- python开发_python关键字
python3.3.2中的关键字如下: The following identifiers are used as reserved words, or keywords of the languag ...
- python语言(四)关键字参数、内置函数、导入第三方模块、OS模块、时间模块
一.可变参数 定义函数时,有时候我们不确定调用的时候会传递多少个参数(不传参也可以).此时,可用包裹(packing)位置参数(*args),或者包裹关键字参数(**kwargs),来进行参数传递,会 ...
- 怎样查看python的所有关键字
关键字是python中具有特定功能的一组词汇, 这些词汇不能用作变量名, 一般会有高亮提示, code时请小心. python的关键字其实也是python的语法核心, 掌握了所有python关键字的用 ...
随机推荐
- Delphi MSComm控件属性
- (九)How to use the audio gadget driver
Contents [hide] 1 Introduction 2 Audio Gadget Driver 1.0 2.1 Enabling the audio gadget driver 2.2 U ...
- 在Python中,如何用一行代码去判定整数二进制中的连续 1
利用字节位操作如何判断一个整数的二进制是否含有至少两个连续的1 的方法有多种,大家第一反应应该想到的是以下的第一种方法. 方法一:从头到尾遍历一遍每一位即可找出是否有连续的1存在 这个方法是最普遍的. ...
- 基础数据 补充 set() 集合 深浅拷贝
一 对字符串的操作 li = ["张曼玉", "朱茵", "关之琳", "刘嘉玲"] s = "_" ...
- linux 命令技巧(转)--history
本文介绍一些关于bash的能够提高效率的技巧,主要是关于历史命令操作和一些快捷键,让你在命令行下工作效率翻倍. 1.history-----最基本的查看历史命令 2.!n-----编号为n的历史命令 ...
- JNetPcap安装及使用
啥是JNetPcap? JNetPcap是由Sly Technologies开发的开源DPI(Deep Packet Inspection)SDK. Java平台底层不支持底层网络操作,需要通过JNI ...
- Linux/Ubantu 安装 idea
wget 使用 wget url (这里的url就是你要下载idea的网站) 在idea官网中 找到 direct link 右键复制链接 在 linux 中 打开 终端命令窗口 (Ctrl +Alt ...
- nginx静态资源服务
静态文件 动态文件 需要算法,函数封装后,返回给浏览器端的 静态资源的服务场景----CDN 异步I/O-----效果不明显 tcp_nopush 注意,须在sendfile开启的前提下 技术思想: ...
- centos 6.5 解压 zip
只查看 zip 文件内容而不解压 unzip -l filename.zip 解压到指定目录(不指定则为当前目录) unzip filename.zip -d /usr/file 压缩文件或目录为 z ...
- Cannot use JSX unless the '--jsx' flag is provided.
在tsx文件中加入html代码后,报错 Cannot use JSX unless the '--jsx' flag is provided. 解决方法: 在tsconfig.json中加入: &qu ...