首页 > 解决方案 > 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 MAPs 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.

标签: pythondictionaryrabbitmqconstants

解决方案


您要求创建循环依赖关系。您希望 analysis_tools.py 依赖于 analysis_tools.py 上的 constants.py 和 constants.py。

拥有一个名为常量的文件通常不是一个好主意。事物应该在功能上属于它们的地方,而不是根据类型。您没有文件调用 classes.py、functions.py、variables.py,原因与您不应该有一个名为 constants.py 的文件相同。

FUNCTION_MAP 明明跟AnalysisTools 有关系,放在同一个文件里就好了。

回复:Q2,你通常只在每个模块中导入你需要的东西。如果没有循环依赖,那么这样做应该没有问题。


推荐阅读