Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 891
Paul Avatar asked Apr 19 '15 16:04

Paul


1 Answers

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 (e.g. 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.

like image 162
chepner Avatar answered Sep 30 '22 00:09

chepner