English 中文(简体)
带有声明的 Python: 存储上下文
原标题:Python with statement: storing context

我试图(如果可能的话)改进下面的数据信息类,或寻找其他解决办法:

class Store(object):

    def __init__( self, contents=None):
        self.contents = contents

class DataContext(object):

    def __init__( self, datastore ) : # datastore is of type store
        self.store = datastore

    def __enter__( self ) :
        self.temp_store = copy.copy( self.store.contents )  # Improve upon this!

    def __exit__( self, type, value, traceback ) :
        self.store.contents = self.temp_store

实例使用:

data = Store( [1,2,3] )
print "Before context: ", data.contents
with DataContext( data ):
    data.contents.append( 4 )         # Tampering with the data 
    print "Within context: ", data.contents

print "Outside context: ", data.contents

产出:

Before context:  [1, 2, 3]
Within context:  [1, 2, 3, 4]
Outside context:  [1, 2, 3]

copy 对于大型数据结构来说成本昂贵。 怎样( 或有没有)一种清洁的方法来只存储上下文中数据结构的变化,然后 undo 在 < code> exit 中保存数据的具体变化?

最佳回答

您可以使用某种检查站。例如,您可以保留一个单独的结构,插入新的元素。当您退出上下文时,您需要将这些新的元素从容器中移除。

显然,这是否值得与深层合作相比,将取决于若干因素,例如:

  1. The underlying container. Not all of them have the same API, so you will need to specialize the checkpointing mechanism for the different supported container types (and that may not be trivial).
  2. What is the ratio of elements before entering the context vs the number of elements inserted while inside the context.

此外,就正确性而言,集装箱类型也影响到这种机制的设计,例如,如果集装箱是一份清单,则需要删除上下文中插入的所有元素。另一方面,如果集装箱是一套,只需在最初不在场的情况下将其删除。

为了简单起见,让我们假设你只对列表感兴趣,而只是支持 append 操作,那么一个可能的解决方案其实很容易:

类 DataContext( 对象) :

def __init__( self, datastore ) : # datastore is of type store
    self.store = datastore
    self.num_added = 0

def __enter__( self ) :
    pass

def __exit__( self, type, value, traceback ) :
    l = len(self.store.contents)
    del self.store.contents[l - self.num_added : l]

def append( self, elem ) :
    self.store.contents.append(elem)
    self.num_added += 1

这绝对是一个非常简单的例子,而且为了从列表的任何地方添加对删除元素的支持,您需要保存列表中操作的某种记录。 日志可以是指定操作类型( 插入、 删除) 及其参数( 如索引、 数据) 的条目列表。 此外, 如果您想要为列表中的所有修改操作提供支持, 您需要使用代理文件或包装来拦截列表中的所有修改操作( 如 < code > append < / code > 、 < code > extend 、 < code > 插入 、 < code > remove < /code > 等 )。

如果您想要去更通用且不仅支持列表, 而且还支持其它种类的容器, 那么您就需要为不同容器的操作提供包装。 例如, 对于 set , 您需要支持 add , remove , update , intersection_ update 等。 要创建从 DataContext 降下来的等级, 以及每种类型的专门操作 。

无论如何,如你所见,执行这个程序的复杂性会大大增加,这取决于你想要多大的通用性。因此,如果你只想要一个专门针对清单的具体解决方案,那么它可能会得到回报来实施它,否则,支付一个集装箱复制件的价格可能更好。

问题回答

您可以使用数据库作为基础存储,执行 Store , 简而言之, ROLLBACK





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...