Skip to content

Instantly share code, notes, and snippets.

@javierarilos
Last active December 28, 2023 05:46
Show Gist options
  • Save javierarilos/6009059 to your computer and use it in GitHub Desktop.
Save javierarilos/6009059 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
from importlib import reload
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()
@mecampbellsoup
Copy link

I think you're missing from importlib import reload, FWIW.

@javierarilos
Copy link
Author

thx for the comment @mecampbellsoup
updated it.
it's been years without looking at python 2.7 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment