Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transparent object versioning in python

I'd like to version objects without them knowing it.

Something like this:

class Versioned(object):
   ...
   def version(self):
       ...

class Foo(Versioned):

   def __init__(self, a):
      self.a = a

foo = Foo(123)
assert foo.version() == 1

foo.a = 1
foo.a = 2
foo.a = 3

assert foo.version() == 4

Is there a simple way of doing this?

like image 675
Srg Avatar asked Sep 19 '26 05:09

Srg


2 Answers

class Versioned(object):
    def __init__(self):
        self.version = 0
    def __setattr__(self, name, value):
        if name == 'version':
            object.__setattr__(self, 'version', value)
        else:
            object.__setattr__(self, name, value)
            object.__setattr__(self, 'version', self.version +1)

Example:

class Foo(Versioned):
    pass

f = Foo()
print f.version  # prints 0

f.a = 1
print f.version # prints 1

f.b = 3
print f.version # prints 2

f.b = 33
print f.version # prints 3
like image 173
rantanplan Avatar answered Sep 20 '26 19:09

rantanplan


Quick hack:

class Versioned(object):
    version = 0

    def __init__(self):
        self.version = 0

    def _increaseVersion(self):
        super(Versioned, self).__setattr__('version', self.version+1)

    def __setattr__(self, attr, value):
        super(Versioned, self).__setattr__(attr, value)
        self._increaseVersion()

    def __delattr__(self, attr):
        super(Versioned, self).__delattr__(attr)
        self._increaseVersion()


class Foo(Versioned):
    def __init__(self, a):
        self.a = a
        super(Foo, self).__init__()


foo = Foo(123)
print 'value:', foo.a
print 'version:', foo.version
foo.a = 23
print 'value:', foo.a
print 'version:', foo.version
del foo.a
print hasattr(foo, 'a')
print 'version:', foo.version

Outputs:

value: 123
version: 1
value: 23
version: 2
False
version: 3
like image 30
Fabian Avatar answered Sep 20 '26 20:09

Fabian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!