Skip to content

Instantly share code, notes, and snippets.

@Hammer2900
Forked from javierarilos/py-code-update.py
Created January 15, 2019 06:13
Show Gist options
  • Save Hammer2900/9186f691653eb87e7200f985a80de80f to your computer and use it in GitHub Desktop.
Save Hammer2900/9186f691653eb87e7200f985a80de80f to your computer and use it in GitHub Desktop.
Sample of reloading a class definition in python. Old and new instances point to the correct class definition.
# writing c1 class definition to module mod1
cs = """
class c1(object):
att = 1
def m1(self):
self.__class__.att += 1
# printing class name, class-id, and the id of the class, which happens to be its memory address
print "uno:", self.__class__, "class-id:", id(self.__class__), "att:", self.__class__.att
"""
f = open('mod1.py', 'w')
f.write(cs)
f.close()
import mod1
from mod1 import c1
# creating instance 1 of class 1
i1 = mod1.c1()
i1.m1()
i1.m1()
# now we are going to update our c1 class definition
# so that the python interpreter realizes the class definition has changed:
# we have to either delete the .pyc (python compiled) file, or sleep 1 second so that .py and .pyc files have different date.
#from time import sleep
#sleep(1)
import os
os.remove('mod1.pyc')
# changing c1 class definition
cs2 = """
class c1(object):
att = 1000
def m1(self):
self.__class__.att += 1
# printing class name, class-id, and the id of the class, which happens to be its memory address
print "dos:", self.__class__, "class-id:", id(self.__class__), "att:", self.__class__.att
"""
f = open('mod1.py', 'w')
f.write(cs2)
f.close()
# force reload class changes from filesystem
reload(mod1)
import mod1
from mod1 import c1
# creating instance 2 of class 1
i2 = mod1.c1()
# now, the behaviour of i1 and i2 match their original class definitions, not current c1.
i2.m1()
i1.m1()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment