Created
July 31, 2012 11:12
-
-
Save erikkaplun/3216278 to your computer and use it in GitHub Desktop.
transparent object restarts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Restartable(object): | |
@classmethod | |
def __new__(cls, *args, **kwargs): | |
ret = super(Restartable, cls).__new__(*args, **kwargs) | |
ret.__initargs__ = (args[1:], kwargs) | |
return ret | |
# this is something like a clone with __getinitargs__ but let's not call | |
# it a clone because it's semantically different--i.e. explicitly discards | |
# any state other than the initial one. | |
def restart(self): | |
print "restarting %s with %s" % (self, self.__initargs__) | |
init_args, init_kwargs = self.__initargs__ | |
return type(self)(*init_args, **init_kwargs) | |
class Foo(Restartable): | |
def __init__(self, a, b): | |
print "Foo(a=%s, b=%s)" % (repr(a), repr(b)) | |
class Bar(Foo): | |
def __init__(self, extra, *args, **kwargs): | |
super(Bar, self).__init__(*args, **kwargs) | |
print "Bar(extra=%s)" % repr(extra) | |
foo = Foo(1, 2) | |
foo = foo.restart() | |
bar = Bar('extra', 4, 5) | |
bar = bar.restart() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment