【发布时间】:2021-05-12 02:51:25
【问题描述】:
我有一个文件 test.py 与
list_sample = [1,2,4]
现在,我想从另一个文件追加到列表中
例如:test2.py
list_sample =+ [10,11]
# also I have many other things in this script
a=10
c=10+a
并将test.py修改为
list_sample = [1,2,4]
# I want to import all the variables from test2.py but also append the list_sample
# I cant do that directly in this file. Because this is like blueprint
from .test2 import *
print(a+30)
print(list_sample)
但这给出了一个错误 list_sample not defined
我可以做到这一点的唯一方法将 test2.py 更改为
list_sample = [1,2,4,10,11]
# also I have many other things in this script
a=10
c=10+a
我还有一个选择是将 test2.py 更改为
from .test import list_sample
list_sample += [10,11]
# also I have many other things in this script
a=10
c=10+a
但这会导致循环导入
结论
这是不可能的,所以我决定就这样。在test2.py 中添加一些隔离
# variables from master file
# copy them from the test.py
list_sample = [1,2,3]
# changes to variables from master file
list_sample =+ [10,11]
# new variables
a=10
c=10+a
我想要这个的原因
在 Django 中,我有 settings.py,其中我有 INSTALLED_APPS 列表
我在我的电脑上工作时使用django_extensions,但是当我将此代码分享给其他人时,我不希望其他人依赖django_extensions
通常在settings.py 中我们可以使用DEGUB=True 进行操作,即
if DEBUG=True:
INSTALLED_APPS =+ INSTALLED_APPS+["django_extensions"]
但这与DEBUG有关
但我正在寻找的是不同的人都使用DEBUG=TRUE
所以我看到有人在下面这样做
setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ordered_model',
# new apps created
'users',
'apps',
]
if os.path.exists(os.path.join(BASE_DIR, "custom_settings.py")):
from .custom_settings.py import *
在custom_settings.py 中添加INSTALLED_APPS 和django_extensions
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ordered_model',
# new apps created
'users',
'apps',
'django_extensions'
]
我打算让这个更通用的类型,所以我正在工作的任何项目我只需将 custom_settings.py 文件复制粘贴到带有 settings.py 的文件夹中并完成我的工作并再次删除 custom_settings.py 或(添加 gitignore) ,因此使用此代码的其他人不必担心我的设置。
所以现在我会在custom_settings.py这样调整
# THIS PART MANUALLY COPY PASTE FROM settings.py
INSTALLED_APPS = [
........ COPY PASTE FROM settings.py
]
# my additional apps i want to use
INSTALLED_APPS =+ ["django_extension"]
【问题讨论】:
-
这不是一个好习惯。
test2.py应该包含进行更改的函数,test.py可以导入并运行它们。 -
那你不了解需求。 Python 不是这样工作的。一个模块无权访问另一个模块的全局变量。必须导入名称。
-
这似乎是XY problem。您要满足的确切要求是什么?请edit澄清。
-
这故意很难,因为这是“远处的诡异动作”,不应该容易。人们不希望导入一个命名空间会改变其他命名空间中的内容。
-
@Santhosh 请编辑以包含您在最近评论中提到的内容。我还建议添加django 标签,因为我确信其他 Django 开发人员也有类似的问题。