golang的defer语句的Python等价物

ttp71kqs  于 2023-04-29  发布在  Go
关注(0)|答案(7)|浏览(118)

如何在python中实现类似go中的defer语句?
Defer将函数调用压入堆栈。当包含defer语句的函数返回时,在defer语句最初所在的作用域中,一个接一个地弹出并执行被defer的函数调用。Defer语句看起来像函数调用,但在弹出之前不会执行。
去它是如何工作的例子:

func main() {
    fmt.Println("counting")

    var a *int
    for i := 0; i < 10; i++ {
        a = &i
        defer fmt.Println(*a, i)
    }

    x := 42
    a = &x

    fmt.Println("done")
}

字符串
输出:

counting
done
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
0 0


Go用例示例:

var m sync.Mutex
func someFunction() {
    m.Lock()
    defer m.Unlock()
    // Whatever you want, with as many return statements as you want, wherever.
    // Simply forget that you ever locked a mutex, or that you have to remember to release it again.
}

gblwokeq

gblwokeq1#

要模拟defer fmt.Println(*a, i)示例,可以使用contextlib.ExitStack

#!/usr/bin/env python3
from contextlib import ExitStack
from functools import partial

print("counting")
with ExitStack() as stack:
    for i in range(10):
        a = i
        stack.callback(partial(print, a, i))

    x = 42
    a = x
    print("done")

字符串

Output

counting
done
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
0 0


很容易模拟互斥体的情况:

def some_function(lock=Lock()):
    with lock:
        # whatever

h7appiyu

h7appiyu2#

Python的with语句与Go语言的defer语句的作用类似。
Python中类似的代码是:

mutex = Lock()

def someFunction():
    with mutex:
        # Whatever you want, with as many return statements
        # as you want, wherever. Simply forget that you ever
        # locked a mutex, or that you have to remember to 
        # release it again.

字符串

ymzxtsji

ymzxtsji3#

我做了一个there(与2.x兼容):

@defers_collector
def func():
    f = open('file.txt', 'w')
    defer(lambda: f.close())

    defer(lambda : print("Defer called!"))

    def my_defer():
    recover()

    defer(lambda: my_defer())

    print("Ok )")
    panic("WTF?")

    print("Never printed (((")

func()
print("Recovered!")

字符串
defers_collector的来源是:

# Go-style error handling

import inspect
import sys

def panic(x):
    raise Exception(x)

def defer(x):
    for f in inspect.stack():
    if '__defers__' in f[0].f_locals:
        f[0].f_locals['__defers__'].append(x)
        break

def recover():
    val = None
    for f in inspect.stack():
    loc = f[0].f_locals
    if f[3] == '__exit__' and '__suppress__' in loc:
        val = loc['exc_value']
        loc['__suppress__'].append(True)
        break
    return val

class DefersContainer(object):
    def __init__(self):
    # List for sustain refer in shallow clone
    self.defers = []

    def append(self, defer):
    self.defers.append(defer)

    def __enter__(self):
    pass

    def __exit__(self, exc_type, exc_value, traceback):
    __suppress__ = []
    for d in reversed(self.defers):
        try:
            d()
        except:
            __suppress__ = []
            exc_type, exc_value, traceback = sys.exc_info()
    return __suppress__

def defers_collector(func):
    def __wrap__(*args, **kwargs):
    __defers__ = DefersContainer()
    with __defers__:
        func(*args, **kwargs)
    return __wrap__

cedebl8k

cedebl8k4#

部分受@DenisKolodin answer启发的 defer 实现可作为pygolang2的一部分提供:

wc = wcfs.join(zurl)    │     wc = wcfs.join(zurl)
   defer(wc.close)         │     try:
                           │        ...
   ...                     │        ...
   ...                     │        ...
   ...                     │     finally:
                           │        wc.close()

字符串

unftdfkk

unftdfkk5#

这个对jfs' answer的补充在装饰器的帮助下进一步推动了ExitStack的想法:

@with_exit_stack
def counting(n, stack):
    for i in range(n):
        stack.callback(print, i)

@with_exit_stack
def locking(lock, stack):
    stack.enter_context(lock)
    # whatever

字符串
with_exit_stack定义如下:

import functools
import contextlib

def with_exit_stack(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        with contextlib.ExitStack() as stack:
            return func(*args, **kwargs, stack=stack)

    return wrapper

9avjhtql

9avjhtql6#

为了好玩,我试着做了一个等价的(只是作为概念验证进行测试)
这里是:

import os
import inspect

class defer:
    """
    Proof of concept for a python equivalent of golang's defer statement

    Note that the callback order is probably not guaranteed

    """
    def __init__(self, callback, *args, **kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

        # Add a reference to self in the caller variables so our __del__
        # method will be called when the function goes out of scope
        caller = inspect.currentframe().f_back
        caller.f_locals[b'_' + os.urandom(48)] = self

    def __del__(self):
        self.callback(*self.args, **self.kwargs)

字符串
使用示例:

def main():
    first()
    second()

def first():
    print('- first')
    defer(lambda: print('   - deferred'))
    print('- first exit')

def second():
    print('- second')      

if __name__ == '__main__':
    main()

zd287kbt

zd287kbt7#

有点晚了,但我建立了一个pip-installable库,它就是这样做的!查看python-defer

from defer import defer

def foo():
  print(", world!") in defer
  print("Hello", end="")
  # do something that might fail...
  assert 1 + 1 == 3

个字符

相关问题