Getting corresponding module from function

后端 未结 4 1231
深忆病人
深忆病人 2020-12-09 15:24

I want to modify a module xyz and its functions like that:

def modify(fun):
    modulename = fun.__module__ # this is string. ok, but not enough

import xyz
         


        
4条回答
  •  温柔的废话
    2020-12-09 16:21

    You do not want to do this.

    1. It does not work. Imagine you defined a function in module abc and then imported it in xyz. test.__module__ would be 'abc' when you called modify(xyz.test). You would then know to change abc.test and you would not end up modifying xyz.test at all!

    2. Monkey patching should be avoided. Fooling with the global state of your program is ill-advised. Instead of doing this, why cannot you just make the new, modified thing and use it?

提交回复
热议问题