为什么需要热替换
代码热替换是指:程序代码修改后,程序不用重启就可以生效。这个特性很有用,特别是有状态程序,可以及时修改程序逻辑,而不用担心状态丢失(重启)。有些编程语言在语言层面上就实现了代码热替换的功能,如erlang。Python本身没有支持代码热替换,其灵活性和开放性为实现代码热替换提供途径。
Python编译机制
Python代码编译后,每个作用域都有一个PyCodeObject与之对应,最外层就是模块的PyCodeObject。Python内置函数compile可以完成代码的编译:
>>> # 测试代码
>>> code = '''
... class A(object):
... def __init__(self, value):
... self.value = value
... def get(self):
... return self.value
...
... def get(value):
... return value
... '''
>>>
>>> # 调用compile编译,参数参考help(compile)
>>> co = compile(code, 'test', 'exec')
>>>
>>> # 模块代码编译结果:test是代码文件名,虽然这里没有用到文件
>>> co
<code object <module> at 0x7fd1f8e8a6b0, file "test", line 2>
>>>
>>> # 模块PyCodeObject的名字,类名A和函数名get都在这
>>> co.co_names
('object', 'A', 'get')
>>>
>>> # 模块PyCodeObject的常量:里面包含两个PyCodeObject,一个跟类A对应,一个跟函数get对应
>>> co.co_consts
('A', <code object A at 0x7fd1f8e8a630, file "test", line 2>, <code object get at 0x7fd1f8e8abb0, file "test", line 8>, None)
>>>
>>> # 看看类A的PyCodeObject
>>> class_code = co.co_consts[1]
>>> class_code
<code object A at 0x7fd1f8e918b0, file "test