How to reload the code of a method of class object in Python?

后端 未结 4 2278
予麋鹿
予麋鹿 2020-12-20 00:24

I\'m find a way to reload the method of a class object at runtime,here is the example: I have define a class A firstly which lies on the file test.py.

class          


        
4条回答
  •  情歌与酒
    2020-12-20 00:54

    The question formulates a powerful tool I frequently use when developing and experimenting with new ideas on architecture and algorithms for python and wish to reload specific implementations without disturbing current locals.

    I use a simplistic approach of

    importlib.reload(my_module)
    my_instance.my_method = types.MethodType(my_class.my_method, my_instance)
    

    my_module has been pared down to only define function and class implementations. For the few creation of global values at a module level that I have, I include those in other modules so they do not get clobbered on reload as importlib.reload only does a shallow reload.

    I have some utility functions specific for my working style that uses the above technique in facilitating reloading of modules, classes and functions that I list.

    This approach helps me more explicitly see how I'm modifying my runtime logic when I do so. iPython does similar things and has similar goals as the above, but for my purposes it is too magical, bloated and poorly designed, with its API thinly documented. It is far too logically coupled with jupyter and it feels like the expectation of it API designers is that the API will never be used outside of that context so no effort has been made in proper abstractions - a rather self fulfilling prophecy.

提交回复
热议问题