在我對過於複雜簡單的東西的無盡追求中,我正在研究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