In Python, how do you change an instantiated object after a reload?

前端 未结 7 1616
南方客
南方客 2021-02-04 06:25

Let\'s say you have an object that was instantiated from a class inside a module. Now, you reload that module. The next thing you\'d like to do is make that reload affect that c

7条回答
  •  爱一瞬间的悲伤
    2021-02-04 07:19

    My approach to this is the following:

    1. Look through all imported modules and reload only those with a new .py file (as compared to the existing .pyc file)
    2. For every function and class method that is reloaded, set old_function.__code__ = new_function.__code__.
    3. For every reloaded class, use gc.get_referrers to list instances of the class and set their __class__ attribute to the new version.

    Advantages to this approach are:

    • Usually no need to reload modules in any particular order
    • Usually only need to reload the modules with changed code and no more
    • Don't need to modify classes to keep track of their instances

    You can read about the technique (and its limitations) here: http://luke-campagnola.blogspot.com/2010/12/easy-automated-reloading-in-python.html

    And you can download the code here: http://luke.campagnola.me/code/downloads/reload.py

提交回复
热议问题