python - Importing constants (function names) from external file
问题描述
This is the file structure:
root_dir/
├── analysis_tools
│ ├── analysis_tools.py
├── others
│ ├── constants.py
├── rabbit_wrappers
│ ├── rabbit_wrapper.py
└── utils
I am working on a workflow implemented using RabbitMq. This is the brief psuedo-code: 1. Task added to RabbitMQ queue 2. Autoscaler spins up Virtual Machine based on Queue 3. Virtual Machine turns on and consumes from the queue
There is one type of machine per queue. So if there is a message in queue1, I need to run func1. If queue2, i need to run func2.
func[n] consumes from queue[n]
from analysis_tools.analysis_tools import AnalysisTools
runner = AnalysisTools()
FUNCTION_MAP = {
'func1' : runner.func1,
'func2' : runner.func2
}
QUEUE_MAP = {
'func1' : "queue1",
'func2' : "queue2"
}
I have a function_map and a queue_map. I pass the function to run (func1/func2) in via command-line argument. Based on what function it's running, it automatically attaches and consumes from the relevant queue.
What I want to do save the FUNCTION_MAP
and QUEUE_MAP
inside others/constants.py
. Then I want to be able to call thees functions in both analysis_tools/analysis_tools.py
and rabbit_wrappers/rabbit_wrapper.py
The problem is when I keep my two MAP
s in constants, it throws an error since it cannot find "runner", and I don't want to/probably shouldn't be instantiating an object of AnalysisTools in my constants.py
file.
So basically, 2 questions.
Q1. How can I save my function_map externally, and call it?
I could call the runner from where I've called the function like so runner.FUNCTION_MAP["func1"]()
Q2. How can I import the constants generally?
This from others.constants import *
does not work.
解决方案
您要求创建循环依赖关系。您希望 analysis_tools.py 依赖于 analysis_tools.py 上的 constants.py 和 constants.py。
拥有一个名为常量的文件通常不是一个好主意。事物应该在功能上属于它们的地方,而不是根据类型。您没有文件调用 classes.py、functions.py、variables.py,原因与您不应该有一个名为 constants.py 的文件相同。
FUNCTION_MAP 明明跟AnalysisTools 有关系,放在同一个文件里就好了。
回复:Q2,你通常只在每个模块中导入你需要的东西。如果没有循环依赖,那么这样做应该没有问题。
推荐阅读
- javascript - 当键盘出现在 IOS 上时,react-native 中的组件模式无法正确调整大小
- pandas - Pandas DataFrames 与 Spyder 4 中的新对象资源管理器一起显示
- android - unitTests.returnDefaultValues 在 gradlew 中运行但在 Android Studio 中运行时有效
- performance - for 循环中断减慢 OpenCL 内核
- android - Xamarin Android 自定义操作栏 - 出了点问题
- unit-testing - Express和sinon:app.use回调函数测试
- php - Aramex 货运跟踪 API 返回 err02
- sql - 没有为 1 个或多个必需参数提供值。更新 SQL
- c++ - 学生评分问题的无限循环(黑客等级)
- java - 分裂
, 有效地使用 Regex/Split() (?)