python - 在模块级别或类内定义列表
问题描述
我有一个类方法,它通过将字典与列表进行比较来验证字典是否包含我期望的所有键。
目前,我在班级的模块级别定义了集合,如下所示:
expected_keys = {
'key1',
'key2',
'key3',
'key4',
}
class Spam(object):
def __init__(self, config_dict):
try:
self.validate_configs(configs)
except TypeError, ValueError:
raise
...
def validate_configs(self, config_dict):
if not isinstance (config_dict, dict):
raise TypeError('Config structure is not a dictionary.')
if not expected_keys == config_dict.keys():
raise ValueError('Config dict does not have all necessary keys.')
这是做到这一点的最佳(性能和实践)方式吗?我计划一次实例化数百个这样的对象,我不确定当前的方法是否会导致性能下降。真正的expected_keys
集合也包含约 30 个条目。只要我正确地做事,我就可以克服它在我的源文件中的丑陋程度(“应该有一种——最好只有一种——明显的方法”)。
解决方案
扩展@PM2Ring 的评论,您应该做一些事情:
1.) 将您的更改expected_keys
为 a set
(目前是 a tuple
。一组用 表示{}
)。class attribute
根据@PM2Ring 的评论,如果它是针对类对象固定的,则可以通过将其作为 a 来保持它的整洁:
class Spam(object):
expected_keys = {
'key1',
'key2',
'key3',
'key4',
}
def __init__(self, config_dict):
# continue defining the rest of your class...
2.) 更改您的最后一次验证:
if not expected_keys.issubset(config_dict.keys()):
raise ValueError('Config dict does not have all necessary keys.')
这将检查是否config_dict
包含您的所有 . expected_keys
,但仍将验证是否config_dict
有其他与预期不同的键。
如果根据您的评论,config_dict
必须具有确切的键(不多也不少)expected_keys
,那么您应该验证为:
if not expected_keys == config_dict.keys():
raise ValueError('Config dict does not have all necessary keys.')
推荐阅读
- c# - 有没有办法在互操作编组的对象上实现 INotifyPropertyChanged 而不会影响二进制布局?
- google-apps-script - 谷歌应用脚本失败总结
- java - 在片段内访问 TextView 会产生 NullPointerException
- html - 如何将项目符号添加到电子邮件模板的 .Body 部分?
- sql - 使用 CTE 更新 Snowflake
- events - Slack 事件 API - 用户提及
- c# - 如何从 Unity、C# 推送(附加)Firebase 实时数据库中的列表?
- java - 在 main 方法 java 之外初始化一个对象
- c++ - 为什么即使我安装了 fltk,我也不能使用 Stroustrup 的 PPP 的标头?
- android - 是否有学习如何创建此 xml 视图的指南或链接?