简体   繁体   中英

Replace function in main module from imported module in Python

Is it possible to set a global variable in the main module from an imported module (using a string) in python?

(Yes I know this isn't best practice.)

Ultimately I want it to look something like this:

main.py

import mod
def func():
  print('failure')
mod.run(func)
func()

mod.py

def func2():
    print('success')
def run(f):
    globals()[f.__name__] = func2

The result is 'failure' because global is relative to the module.

I'm wanting to overwrite the variable func with func2 , from the module.

Another caveat: the variable func changes, so I need to refer to it be the f.__name__ string

I'm aware that this approach wouldn't work if the name of func were changed before it's changed via mod.run(func) .

My question: Is it possible to change the function in the main module from an imported module, without changing the code in the above example main.py ? If so, how?

Rather than change what the name func is bound to, you can change the code that function func is bound to actually executes.

def func2():
    print('success')
def run(f):
    f.__code__ = func2.__code__

This modifies the actual function object referenced by func , and only partially using the code above, so further surgery may be needed (eg to update func.__name__ to be func2 instead of func ), and you may want to make a real copy of func before monkey patching it like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM