Skip to content

Instantly share code, notes, and snippets.

@jkeifer
Last active March 30, 2018 18:34
Show Gist options
  • Save jkeifer/fc8c1a55000c595ba5259ac6aa669a41 to your computer and use it in GitHub Desktop.
Save jkeifer/fc8c1a55000c595ba5259ac6aa669a41 to your computer and use it in GitHub Desktop.
How to do in-place object replacement in python
from __future__ import print_function
_id_seq = 1
def id_seq():
global _id_seq
num = _id_seq
_id_seq += 1
return num
class Test(object):
def __init__(self, arg, id=id_seq()):
self.id = id
self.arg = arg
# this method is the star of the show and the
# reason this whole thing is interesting
def update(self, new_arg):
# we replace the current instance with the
# content of a new instance, so all references
# to the old instance will return the new instance
new_inst = Test(new_arg, id=self.id)
self.__dict__.update(new_inst.__dict__)
# LET'S TEST THIS OUT!
# we create some test instances
t1 = Test('t1')
t2 = Test('t2')
t3 = Test('t3')
# we put all the test instances in to a dict, as
# that will store one of our references
d = {t.id: t for t in [t1, t2, t3]}
# let's see what we have
print(d)
[print(item.arg) for item in d.values()]
# now we update using one of our two stored references
t1.update('t4')
t2.update('t5')
t3.update('t6')
# we can delete these references to show the
# dict ones are different
del t1
del t2
del t3
# now let's print the dict again
print(d)
[print(item.arg) for item in d.values()]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment