Dynamically adding a function to an existing imported module
This can be a very naive question, and it might be better to ask it with an example:
module1.py
import module2
def new_func():
print(var_string)
module2.new_func = new_func
module2.func()
module2.new_func()
module2.py
var_string = "i'm the global string!"
def func():
print(var_string)
result
> python module1.py
i'm the global string!
Traceback (most recent call last):
File "module1.py", line 8, in <module>
module2.new_func()
File "module1.py", line 4, in new_func
print(var_string)
NameError: name 'var_string' is not defined
So my question is this: Is it possible to inject a function into a module and have this global namespace update accordingly?
Related: A global variable defined in the main script cannot be accessed by a function defined in another module Please note that I know that sharing globals is a bad idea and I also know that a config module would be a good compromise for this, but also note that this is not what I am trying to achieve.
source to share
You might think this is useful, but very little python code is written this way, and I think most Python programmers will be confused with code that does it. Modifying a module after importing it (monkeypatching) is usually reduced because it is very easy to do the wrong thing and cause strange errors.
You made an analogy comparing it to overriding / extending methods in a class, but if that's really what you want to do, why not just use a class? The class features make it much safer and easier to do this.
Your code will work if you do the following:
from module2 import var_string
#or..
from module2 import *
But I'm not sure if this is the solution you are looking for. Anyway, I'm not personally trying to get this code to work, it struggles with the way the pin code is normally written. If you have a practical example of code that you think will be improved by dynamically modifying modules, I'd love to see it. It's a bit difficult to see the advantage with the example code you gave.
source to share
I don't understand what you want and what this line is supposed to do "module2.new_func = new_func" because you don't have the new_funcin module2 function. But if you want to reprogram a variable in every module, you cannot use this:
Module1:
import module2
def new_func():
print(var_string)
new_class=module2.MyStuff()
var_string=new_class.func()
new_func()
Module 2:
class MyStuff:
def __init__(self):
self.var_string = "i'm the global string!"
def func(self):
print(self.var_string)
return self.var_string
source to share