如何在代码执行期间更新传递给上下文管理器的参数?

2024-09-27 00:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

node被传递给上下文管理器,我想在开始时锁定它,然后做一些工作,最后解锁节点。在cd1{cd1>执行过程中,{do}是如何被更新的?在

这段代码在Python2.7中运行

from contextlib import contextmanager


@contextmanager
def call(begin, end, *args, **kwargs):
    begin(*args, **kwargs)
    try:
        yield
    finally:
        end(*args, **kwargs)


def lockFunc(*args):
    print 'in lockFunc'
    print 'lock %s' %args[0]


def unlockFunc(*args):
    print 'in unlockFunc'
    print 'unlock %s' %args[0]


node = 'old-node'
with call(lockFunc, unlockFunc, node):

    print 'in with'
    # update node value here
    node = 'new-node'

但结果是

^{pr2}$

我怎样才能让unlockFunc知道node已更改。在

编辑:我尝试过使node成为一个列表,但这不起作用。在

编辑2: 我试着用一个列表,它是这样工作的。在

node = ['old-node']
with call(lockFunc, unlockFunc, node):

    print 'in with'
    node[0] = 'new-node'

Tags: innodedefwithargscalloldkwargs
2条回答

我找到了更好的解决办法。在

class call(object):

    def __init__(self,begin, end, *args, **kwargs):
        self.begin = begin
        self.end = end
        self.args = args
        self.kwargs = kwargs

    def __enter__(self):
        self.begin(*self.args, **self.kwargs)
        return self

    def __exit__(self,exc_type,exc_val,trcback):
        self.end(*self.args, **self.kwargs)

def lockFunc(*args):
    print 'in lockFunc', args
    print 'lock %s' %args


def unlockFunc(*args):
    print 'in unlockFunc'
    print 'unlock %s' %args

node = 'old-node'

with call(lockFunc, unlockFunc, node) as c:
    print 'in with'
    # update node value here
    c.args = ('new-node',)

{{cd2>所引用的对象{cd1>没有改变^的问题。在

相反,您需要告诉对象要更改,并且只能对可变对象执行此操作;字符串不是可变的。一个列表可以,但我认为一个类可能更清楚一些:

from contextlib import contextmanager

class Node(object):
    def __init__(self,value):
        self.value=value

    def update(self, newvalue):
        self.value = newvalue

    def __str__(self):
        return str(self.value)

@contextmanager
def call(begin, end, *args, **kwargs):
    begin(*args, **kwargs)
    try:
        yield
    finally:
        end(*args, **kwargs)


def lockFunc(*args):
    print 'in lockFunc'
    print 'lock %s' %args[0]


def unlockFunc(*args):
    print 'in unlockFunc'
    print 'unlock %s' %args[0]


node = Node('old-node')
with call(lockFunc, unlockFunc, node):

    print 'in with'
    # update node value here
    node.update('new-node')

产生

^{pr2}$

(Ubuntu 14.04,Python 2.7.6)

相关问题 更多 >

    热门问题