gpt4 book ai didi

Python导入lib类似 "import * from XXX"

转载 作者:行者123 更新时间:2023-12-01 04:09:57 24 4
gpt4 key购买 nike

我有以下配置文件结构:

app
\config
\development
\__init__.py
\settings.py
\app_config.py
\production
\__init__.py
\settings.py
\app_config.py
\testingpy
\settings.py
\app_config.py
\settinngs.py
\app_config.py

实际上app.config.settings只需检查环境变量RUNTIME_ENV(可以是development|product|testing,相当于之一code>config 的子文件夹)并加载相应的设置。

我只知道使用 importlib 进行导入,它将模块作为局部变量返回给我,我被迫编写类似的内容:

SCALA_URL = imported_settings.SCALA_URL
REDIS_URL = imported_settings.REDIS_URL
SOME_SETTINGS_VAR = imported_settings.REDIS_URL
.... tons of duplicated strings here, i.e. variables names are the same ...

有没有办法做一些类似于python表达式的事情:from config.${RUNTIME_ENV}.settings import *

最佳答案

globals() 的返回值是可变的。你可以这样做:

imported_foo = importlib.import_module('foo')
globals().update(vars(imported_foo))

请注意,这会将以下划线前缀的内容导入到全局命名空间中。如果您想排除这些内容,请编写一个仅包含您想要的内容的字典理解。例如:

globals().update({name: value 
for name, value in vars(imported_foo).items()
if not name.startswith('_')})

不适用于 locals() ,它返回一个只读值。这样做不太可能( import * 进入非全局命名空间),因为 Python 必须在编译时知道所有局部变量的名称才能生成正确的 LOAD_FOO字节码中的指令(以及各种其他有趣的问题,例如识别 closure 捕获的变量)。你会发现import *在函数或类中是非法的:

>>> def foo():
... from foo import *
...
File "<stdin>", line 1
SyntaxError: import * only allowed at module level
>>>

这不仅仅是“import * 是糟糕的设计”的问题。这是一个基本的语言限制,无法通过 importlib 来解决。 .

关于Python导入lib类似 "import * from XXX",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35094747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com