延迟函数defer

我们知道在Golang中有一个关键字defer,用它来声明在函数调用前,会让函数*延迟**到外部函数退出时再执行,注意,这里的退出含义:函数return返回或者函数panic退出

defer的特性

  1. defer函数会在外层函数执行结束后执行
package main

import "fmt"

func main() {
defer fmt.Println(2)
fmt.Println(1) }
/* output:
1
2
*/
  1. defer函数会在外层函数异常退出时执行
package main

import "fmt"

func main() {
defer fmt.Println(2)
panic(1) }
/* output:
2
panic: 1 goroutine 1 [running]:
main.main()
/tmp/sandbox740231192/prog.go:7 +0x95
*/

3.如果函数中有多个defer函数,它们的执行顺序是LIFO:

package main

import "fmt"

func main() {
defer fmt.Println(2)
defer fmt.Println(3)
fmt.Println(1)
}
/*output:
1
3
2
*/

defer的用途

释放资源

比如打开文件后关闭文件:

package main

import "os"

func main() {
file, err := os.Open("1.txt")
if err != nil {
return
}
// 关闭文件
defer file.Close() // Do something... }

又比如数据库操作操作后取消连接

func createPost(db *gorm.DB) error {
conn := db.Conn()
defer db.Close() err := conn.Create(&Post{Author: "Draveness"}).Error return err
}

recover恢复

package main

import "fmt"

func main() {
defer func() {
if ok := recover(); ok != nil {
fmt.Println("recover")
}
}() panic("error")
}
/*output:
recover
*/

总结

  1. defer函数总会被执行,无论外层函数是正常退出还是异常panic
  2. 如果函数中有多个defer函数,它们的执行顺序是LIFO

在Python中的写一个defer

看到defer这么好用,Pythoneer也可以拥有吗?当然

家里(Python)的条件

Python中有一个库叫做contextlib,它有一个类叫ExitStack,来看一下官网的介绍

A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data.

Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state.

Since registered callbacks are invoked in the reverse order of registration 这句是关键,他说注册的回调函数是以注册顺序相反的顺序被调用,这不就是defer函数的第二个特性LIFO吗?

再看下ExitStack类:

class ExitStack(ContextManager[ExitStack]):
def __init__(self) -> None: ...
def enter_context(self, cm: ContextManager[_T]) -> _T: ...
def push(self, exit: _CM_EF) -> _CM_EF: ...
def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ...
def pop_all(self: _U) -> _U: ...
def close(self) -> None: ...
def __enter__(self: _U) -> _U: ...
def __exit__(
self,
__exc_type: Optional[Type[BaseException]],
__exc_value: Optional[BaseException],
__traceback: Optional[TracebackType],
) -> bool: ...

可以看到它实现了是上下文管理器的协议__enter____exit__,所以是可以保证defer的第一个特性:defer函数总会被执行

让我们来测试一下

import contextlib

with contextlib.ExitStack() as stack:
stack.callback(lambda: print(1))
stack.callback(lambda: print(2)) print("hello world")
raise Exception()

输出:

hello world
2
1
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
/defer_test.py in <module>
6
7 print("hello world")
----> 8 raise Exception() Exception:

nice! 这行的通

行动

让我们做一下封装,让它更通用一些吧

类版本,像defer那样

import contextlib

class Defer:
def __init__(self, *callback):
"""callback is lambda function
"""
self.stack = contextlib.ExitStack()
for c in callback:
self.stack.callback(c) def __enter__(self):
pass def __exit__(self, exc_type, exc_val, exc_tb):
self.stack.__exit__(exc_type, exc_val, exc_tb) if __name__ == "__main__":
with Defer(lambda: print("close file"), lambda: print("close conn")) as d:
print("hello world")
raise Exception()

输出:

hello world
close conn
close file
Traceback (most recent call last):
File "defer.py", line 38, in <module>
raise Exception()
Exception

通过配合lambda表达式,我们可以更加灵活

装饰器版本,不侵入函数的选择

import contextlib

def defer(*callbacks):
def decorator(func):
def wrapper(*args, **kwargs):
with contextlib.ExitStack() as stack:
for callback in callbacks:
stack.callback(callback)
return func(*args, **kwargs)
return wrapper
return decorator @defer(lambda: print("logging"), lambda: print("close conn..."))
def query_exception(db):
print("query...")
raise Exception() if __name__ == "__main__":
db = None
query_exception(db)

输出:

query...
close conn...
logging
Traceback (most recent call last):
File "defer.py", line 43, in <module>
query_exception(db)
File "defer.py", line 25, in wrapper
return func(*args, **kwargs)
File "defer.py", line 38, in query_exception
raise Exception()
Exception

Get!快学起来吧~

Python也可以拥有延迟函数的更多相关文章

  1. Python的函数式编程-传入函数、排序算法、函数作为返回值、匿名函数、偏函数、装饰器

    函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计的基本单元. ...

  2. Python的常用内置函数介绍

    Python的常用内置函数介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.取绝对值(abs) #!/usr/bin/env python #_*_coding:utf-8_ ...

  3. python函数式编程之返回函数、匿名函数、装饰器、偏函数学习

    python函数式编程之返回函数 高阶函数处理可以接受函数作为参数外,还可以把函数作为结果值返回. 函数作为返回值 def laxy_sum(*args): def sum(): ax = 0; fo ...

  4. Python学习笔记之常用函数及说明

    Python学习笔记之常用函数及说明 俗话说"好记性不如烂笔头",老祖宗们几千年总结出来的东西还是有些道理的,所以,常用的东西也要记下来,不记不知道,一记吓一跳,乖乖,函数咋这么多 ...

  5. [python学习] 语言基础—排序函数(sort()、sorted()、argsort()函数)

    python的内建排序函数有 sort.sorted两个. 1.基础的序列升序排序直接调用sorted()方法即可 ls = list([5, 2, 3, 1, 4]) new_ls = sorted ...

  6. python 装饰器修改调整函数参数

    简单记录一下利用python装饰器来调整函数的方法.现在有个需求:参数line范围为1-16,要求把9-16的范围转化为1-8,即9对应1,10对应2,...,16对应8. 下面是例子: def fo ...

  7. Python 函数式编程 & Python中的高阶函数map reduce filter 和sorted

    1. 函数式编程 1)概念 函数式编程是一种编程模型,他将计算机运算看做是数学中函数的计算,并且避免了状态以及变量的概念.wiki 我们知道,对象是面向对象的第一型,那么函数式编程也是一样,函数是函数 ...

  8. Python中的高阶函数与匿名函数

    Python中的高阶函数与匿名函数 高阶函数 高阶函数就是把函数当做参数传递的一种函数.其与C#中的委托有点相似,个人认为. def add(x,y,f): return f( x)+ f( y) p ...

  9. Delphi 延迟函数 比sleep 要好的多

    转自:http://www.cnblogs.com/Bung/archive/2011/05/17/2048867.html //延迟函数:方法一 procedure delay(msecs:inte ...

随机推荐

  1. 查看JVM默认参数及微调JVM启动参数

    目录 查看某个JVM进程堆内存信息 微调JVM启动参数 查看JVM的一些默认参数 参考廖雪峰老师的这篇 JVM调优的正确姿势: https://www.liaoxuefeng.com/article/ ...

  2. 微信小程序云开发-列表下拉刷新

    一.json文件开启页面刷新 开启页面刷新.在页面的json文件里配置两处: "enablePullDownRefresh": true, //true代表开启页面下拉刷新 &qu ...

  3. Java-数组有关

    1.复制数组 复制数组主要有三类方法: 1.使用循环语句逐个赋值数组元素 2.使用System类中的静态方法arraycopy 3.使用clone方法复制数组 对于2,详述如下: arraycopy( ...

  4. PAT乙级:1082 射击比赛 (20分)

    PAT乙级:1082 射击比赛 (20分) 题干 本题目给出的射击比赛的规则非常简单,谁打的弹洞距离靶心最近,谁就是冠军:谁差得最远,谁就是菜鸟.本题给出一系列弹洞的平面坐标(x,y),请你编写程序找 ...

  5. Guava - Set集合

    当我们在统计一个字符串中每个单词出现的次数时,通常的做法是分割字符串,遍历字符串,然后放到一个map里面,来进行统计,Guava中提供了类似功能的集合,Multiset String strWorld ...

  6. 第五十三篇 -- MFC美化界面2

    IDC_STATIC 1. 设置字体样式 方法1:在OnInitDialog()函数中使用以下语句 CFont * f; f = new CFont; f->CreateFont(50, // ...

  7. Spring Data Commons 远程命令执行漏洞(CVE-2018-1273)

    影响版本 Spring Framework 5.0 to 5.0.4 Spring Framework 4.3 to 4.3.14 poc https://github.com/zhzyker/exp ...

  8. Java基础——逻辑运算符、位运算符

    逻辑运算符.位运算符.三元运算符 逻辑运算符  public class Demon05 {     public static void main(String[] args) {          ...

  9. SpringBoot-技术专区-用正确的姿势如何用外置tomcat配置及运行(Tomcat优化分析)

    前提概要 在特别特殊的时候,我们可能需要外置tomcat去运行程序,例如alitomcat等特殊场景,方便我们去定时化开发项目或者其他特殊场景. 外置tomcat执行 pom.xml文件首先更改打包方 ...

  10. webservice接口调用

    package com.montnets.emp.sysuser.biz; import org.apache.axis.client.Call; import org.apache.axis.cli ...