Getting corresponding module from function

后端 未结 4 1235
深忆病人
深忆病人 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 16:04

    Use the inspect module:

    import inspect
    
    def modify(fun):
        module = inspect.getmodule(fun)
    

    This is the same as polling the module from sys.modules using fun.__module__. Although getmodule tries harder even if fun does not have a __module__ attribute.

提交回复
热议问题