社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

将所有默认值移到一个python文件中

Canh • 5 年前 • 1477 次点击  

我有一个python文件,其中包含项目中每一个其他类的所有默认值

# config.py
DEFAULT_WORKER_TYPE = 'A'
DEFAULT_METRIC_TYPE = 'euclid'
...

# worker.py
import config
class Worker:
    def __init__(self, worker_type=config.DEFAULT_WORKER_TYPE):
        pass

# metric.py
import config
class Metric:
    def __init__(self, metric_type=config.DEFAULT_METRIC_TYPE):
        pass

这个很好,但是我想用 Enum 对于 worker_type metric_type 而不是原始字符串以避免输入错误

# config.py
from worker import WorkerType
from metric import MetricType

DEFAULT_WORKER_TYPE = WorkerType.A
DEFAULT_METRIC_TYPE = MetricType.EUCLID

# worker.py
from enum import Enum
import config

class WorkerType(Enum):
    A = 'A'
    B = 'B'

class Worker: # the same

# metric.py
from enum import Enum
import config

class MetricType(Enum):
    EUCLID = 'euclid'
    MANHATTAN = 'manhattan'

class Metric: # the same

现在,在我看来,后一个版本不是很有效,因为它有某种循环导入,如果我的主程序只使用一个文件( worker.py 例如,它仍然需要每隔一个文件导入一次( metric.py 因为 config.py 全部进口。

有没有更好的方法来实现这个目标?

我将所有默认值移动到 配置py 我需要经常用这些值做实验。把所有东西放在一个地方可以帮助我不必记住要更改哪个文件。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46179
 
1477 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Krishal
Reply   •   1 楼
Krishal    6 年前

这些枚举应该在配置文件中,或者至少在值中。如果使用这种方式编程,就不会将config.py文件用作配置文件。做下面这样的事情,但要正确编码。

# config.py
from enum import Enum

class WorkerType(Enum):
    A = 'A'
    B = 'B'

class MetricType(Enum):
    EUCLID = 'euclid'
    MANHATTAN = 'manhattan'

DEFAULT_WORKER_TYPE = WorkerType.A
DEFAULT_METRIC_TYPE = MetricType.EUCLID

# worker.py
import config

class Worker: # the same

# metric.py
import config

class Metric: # the same

只从配置导入所需的内容。它打字少,在我心目中更容易阅读。

Laurent LAPORTE
Reply   •   2 楼
Laurent LAPORTE    6 年前

在imo中,您可以使用经典的方法,将每个类放在一个模块中。

worker_type.py :

import enum

class WorkerType(enum.Enum):
    A = 'A'
    B = 'B'

metric_type.py 以下内容:

import enum

class MetricType(enum.Enum):
    EUCLID = 'euclid'
    MANHATTAN = 'manhattan'

然后您可以这样定义配置文件:

import worker_type
import metric_type

DEFAULT_WORKER_TYPE = worker_type.WorkerType.A
DEFAULT_METRIC_TYPE = metric_type.MetricType.EUCLID

这样,你的 worker.py 保持不变:

import config

class Worker:
    def __init__(self, worker_type=config.DEFAULT_WORKER_TYPE):
        pass