Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 重写python中使用其他模块变量的模块变量_Python 3.x_Variables_Module - Fatal编程技术网

Python 3.x 重写python中使用其他模块变量的模块变量

Python 3.x 重写python中使用其他模块变量的模块变量,python-3.x,variables,module,Python 3.x,Variables,Module,我有一个python模块,在那里我存储我的设置settings.py。此文件包含以下行: BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_URL = 'https://my-base-url.com/test' ... SCORM_TEST_URL = BASE_URL + '/scorm2004testwrap.htm' 我希望允许用户覆盖这些设置,例如使用命令行选项或环境变量。当我这样做时,它对直接变量赋值很有效 imp

我有一个python模块,在那里我存储我的设置
settings.py
。此文件包含以下行:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
BASE_URL = 'https://my-base-url.com/test'
...
SCORM_TEST_URL = BASE_URL + '/scorm2004testwrap.htm'
我希望允许用户覆盖这些设置,例如使用命令行选项或环境变量。当我这样做时,它对直接变量赋值很有效

import settings
settings.BASE_URL = 'test'
然而

settings.SCORM_TEST_URL 
#will print https://my-base-url.com/test/scorm2004testwrap.htm

有没有办法告诉python用重写的值更新这些依赖变量?或者我该如何设计我的程序,它允许覆盖设置,以及设置python模块文件中的变量,因为正如您所看到的,在上面的示例中,它可能需要导入其他python模块,如
os

似乎这是不可行的

当您设置
setting.BASE\u URL=something
时,它现在被重新分配给某个对象,而之前的任何值都消失了,因此它可以工作

但是
SCORM\u-TEST\u-URL
是基于旧的
BASE\u-URL
值创建的,它一旦创建就与
BASE\u-URL
没有关系。因此,除非您基于新的
BASE\u-URL
值重新评估它,否则更改
BASE\u-URL
不会反映在
SCORM\u-TEST\u-URL

我可以想到的一些解决方法如下,像往常一样声明那些需要在模块外部修改的变量

将另一组需要更新的变量放入更新函数中,并使其成为全局变量

内部设置.py

BASE_URL = 'https://my-base-url.com/test'
# ... other var

def update_var():
    global SCORM_TEST_URL
    SCORM_TEST_URL = BASE_URL + '/scorm2004testwrap.htm'
    # added other var accordingly
从其他模块,像往常一样导入设置

import settings
settings.BASE_URL = 'test'
# update variables
settings.update_var()
# settings.SCORM_TEST_URL should be updated now