在我对过于复杂简单的东西的无尽追求中,我正在研究Python中最常见的Python提供全局配置变量的方法,这些变量位于Python egg packages中的典型'config.py'中。在config.py中提供全局配置变量的大多数Pythonic方法?
传统的方式(!啊哈,好醇” 的#define)如下:
MYSQL_PORT = 3306
MYSQL_DATABASE = 'mydb'
MYSQL_DATABASE_TABLES = ['tb_users', 'tb_groups']
因此全局变量进口的下列方式之一:
from config import *
dbname = MYSQL_DATABASE
for table in MYSQL_DATABASE_TABLES:
print table
或:
import config
dbname = config.MYSQL_DATABASE
assert(isinstance(config.MYSQL_PORT, int))
它是有道理的,但有时可以b有点混乱,特别是当你试图记住某些变量的名字时。此外,提供'配置'对象,变量作为属性,可能会更灵活。因此,采取从bpython config.py文件中的领先优势,我想出了:
class Struct(object):
def __init__(self, *args):
self.__header__ = str(args[0]) if args else None
def __repr__(self):
if self.__header__ is None:
return super(Struct, self).__repr__()
return self.__header__
def next(self):
""" Fake iteration functionality.
"""
raise StopIteration
def __iter__(self):
""" Fake iteration functionality.
We skip magic attribues and Structs, and return the rest.
"""
ks = self.__dict__.keys()
for k in ks:
if not k.startswith('__') and not isinstance(k, Struct):
yield getattr(self, k)
def __len__(self):
""" Don't count magic attributes or Structs.
"""
ks = self.__dict__.keys()
return len([k for k in ks if not k.startswith('__')\
and not isinstance(k, Struct)])
;进口类和如下一个 'config.py':
from _config import Struct as Section
mysql = Section("MySQL specific configuration")
mysql.user = 'root'
mysql.pass = 'secret'
mysql.host = 'localhost'
mysql.port = 3306
mysql.database = 'mydb'
mysql.tables = Section("Tables for 'mydb'")
mysql.tables.users = 'tb_users'
mysql.tables.groups = 'tb_groups'
和用于这种方式:
from sqlalchemy import MetaData, Table
import config as CONFIG
assert(isinstance(CONFIG.mysql.port, int))
mdata = MetaData(
"mysql://%s:%[email protected]%s:%d/%s" % (
CONFIG.mysql.user,
CONFIG.mysql.pass,
CONFIG.mysql.host,
CONFIG.mysql.port,
CONFIG.mysql.database,
)
)
tables = []
for name in CONFIG.mysql.tables:
tables.append(Table(name, mdata, autoload=True))
这似乎是一个更具可读性,表达性和灵活性的方式来存储和获取包内的全局变量。
有史以来最蠢的想法?应对这些情况的最佳做法是什么?什么是你的存储和获取你的包内的全局名称和变量的方式?
你已经在这里做了一个决定,可能会或可能不会好。配置本身可以以不同的方式存储,比如JSON,XML,用于* nixes和Windows的不同语法等等。根据谁写配置文件(一个工具,一个人,什么背景?),不同的语法可能更可取。大多数情况下,让配置文件使用与您的程序相同的语言来编写配置文件可能不是一个好主意,因为它会给用户带来太多的权力(可能是您自己,但您自己可能不记得所有可以使用的东西在未来几个月出错)。 – erikbwork 2011-06-01 08:53:07
通常我最终会写一个JSON配置文件。它可以轻松地读入python结构,也可以通过工具创建。它似乎具有最大的灵活性,唯一的代价是可能会让用户烦恼的一些大括号。不过,我从来没有写过鸡蛋。也许这是标准方式。在这种情况下,请忽略我上面的评论。 – erikbwork 2011-06-01 08:55:40
您可以使用“瓦尔(个体经营)”,而不是“自我.__字典__。键()” – Karlisson 2013-12-18 15:19:02