首页 > 解决方案 > 在模块级别或类内定义列表

问题描述

我有一个类方法,它通过将字典与列表进行比较来验证字典是否包含我期望的所有键。

目前,我在班级的模块级别定义了集合,如下所示:

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 个条目。只要我正确地做事,我就可以克服它在我的源文件中的丑陋程度(“应该有一种——最好只有一种——明显的方法”)。

标签: pythonpython-3.xoop

解决方案


扩展@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.')

推荐阅读