Python 向现有导入模块动态添加函数

Python 向现有导入模块动态添加函数,python,module,global-variables,Python,Module,Global Variables,这可能是一个非常幼稚的问题,最好用一个例子来回答: 模块1.py import module2 def new_func(): print(var_string) module2.new_func = new_func module2.func() module2.new_func() var_string = "i'm the global string!" def func(): print(var_string) module2.py import module2

这可能是一个非常幼稚的问题,最好用一个例子来回答:

模块1.py

import module2

def new_func():
    print(var_string)
module2.new_func = new_func

module2.func()
module2.new_func()
var_string = "i'm the global string!"

def func():
    print(var_string)
module2.py

import module2

def new_func():
    print(var_string)
module2.new_func = new_func

module2.func()
module2.new_func()
var_string = "i'm the global string!"

def func():
    print(var_string)
结果

> 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
python模块1.py 我是全球字符串! 回溯(最近一次呼叫最后一次): 文件“module1.py”,第8行,在 模块2.新函数() 文件“module1.py”,第4行,在新函数中 打印(变量字符串) NameError:未定义名称“var_string” 所以我的问题是: 是否可以将函数插入模块并相应地更新其全局命名空间

相关的:
请注意,我知道共享全局变量是一个坏主意,我也知道配置模块将是一个很好的折衷方案,但也请注意,这不是我想要实现的

您可能认为它很有用,但是很少有python代码是这样编写的,我认为大多数python程序员都会对这样做的代码感到困惑。在导入模块后修改模块(monkeypatching)通常会受到轻视,因为它很容易出错并导致奇怪的错误

您将其与重写/扩展类上的方法进行了类比,但如果这确实是您想要做的,为什么不使用类呢?类的特性使得做这种事情更加安全和容易

如果执行以下操作,代码将正常工作:

from module2 import var_string
#or..
from module2 import *

但我不确定这是否是你想要的解决方案。无论哪种方式,我个人都不会试图让这段代码正常工作,这与python代码通常的编写方式是背道而驰的。如果您有一个实际的代码示例,您认为可以通过动态修改模块来改进它,我想看看它。你给出的示例代码有点难看出它的好处。

我不明白你想要什么,以及这个字符串必须做什么“module2.new\u func=new\u func”,因为你没有module2中的函数new\u func。 但是,如果要在每个模块中重置变量,则不能这样使用:

模块1:

import module2

def new_func():
    print(var_string)

new_class=module2.MyStuff()
var_string=new_class.func()
new_func()
模块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

他们没有必要这样做。您可以只使用if语句来确定调用哪个方法,或者将哪些参数传递到方法中。等等……我不同意。我认为这将非常有用。一个类比是动态地将一个方法添加到现有的类中,该类利用该类的其他属性和方法。我还希望这个插入的函数能够被其他模块调用。本质上,我是在动态扩展模块,而无需实际编辑模块的源代码。您需要将print(var_string)更改为print(module2.var_string)@Damiánmentegro No,这不是我想要的。我希望func能够直接访问module2的全局成员,就像它最初是在global2中定义的一样。我从来没有这样做过。但方法是否凌驾于您所说的之上?看看这个链接公平点。一些上下文:我正在使用日志模块,我想向该模块添加一个函数(它使用模块中的其他内容),然后我可以从应用程序中的其他模块引用该函数。这是促使我提出这个问题的原始问题。