繁体   English   中英

Python dict.get() 在密钥存在且有效时抛出 KeyError

[英]Python dict.get() throwing KeyError when the key is there and valid

我有一个将字符串映射到类的字典,以便可以实例化它们:

process_mapper = {VTNotifications.name: VTNotifications}

class 如下所示:

class VTNotifications(AbstractNormaliser):

    # String name for use defining KV
    name = 'vt-notifications-feed'

    def __init__(self, config):
        super().__init__(config)
        self.config = config
        # Add source meta-data
        self.meta_normaliser = MetaDataNormaliser(source='vt-notifications', doc_type='notification',
                                                  event_type='vt-notification')

我编写了一个测试来检查字符串是否确实正确返回,它通过了:

def test_getter():
    class_type = process_mapper.get(VTNotifications.name)
    assert class_type == VTNotifications

但是,当我尝试将实例化 class 所需的完整配置传递给执行所有实例化的方法时,突然,它出现 KeyErrors:

def test_mapped_normaliser():
    processor_name = VTNotifications.name
    normaliser = {'name': processor_name,
                  'config': {'consumer': {'topic': 'some_topic',
                                          'subscription': 'some_subscription'}},
                  'publisher': {'topic': 'some_other_topic'},
                  'project-id': 'some_id'}
    config = {'normalisers': [normaliser]}
    runner = NormaliserRunner(config)
    assert isinstance(runner.processes[processor_name], VTNotifications)



class NormaliserRunner(object):

    def __init__(self, config):
        self.normalisers = config['normalisers']
        self.processes = {}
        self.config = config
        self.map_processes()

    def run(self):
        for process in self.processes.values():
            process.normalise()

    # returns a dict of normaliser processes, and their mapped class implementations instantiated
    def map_processes(self):
        print(f"[*] Using processes mapper with {process_mapper.keys()} keys")
        for normaliser in self.normalisers:
            print(normaliser)
            self.processes[normaliser['name']] = process_mapper.get(
                normaliser['name'])(self.config[normaliser['name']]['config'])
============================= test session starts ==============================
platform linux -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /mnt/c/Users/ARES/Desktop/work/phoenix/normaliser
collected 3 items

test.py ..F                                                              [100%]

=================================== FAILURES ===================================
____________________________ test_mapped_normaliser ____________________________

    def test_mapped_normaliser():
        processor_name = VTNotifications.name
        normaliser = {'name': processor_name,
                      'config': {'consumer': {'topic': 'some_topic',
                                              'subscription': 'some_subscription'}},
                      'publisher': {'topic': 'some_other_topic'},
                      'project-id': 'some_id'}
        config = {'normalisers': [normaliser]}
>       runner = NormaliserRunner(config)

test.py:31: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
main.py:14: in __init__
    self.map_processes()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <normaliser.main.NormaliserRunner object at 0x7ff3d0e7fc10>

    def map_processes(self):
        print(f"[*] Using processes mapper with {process_mapper.keys()} keys")
        for normaliser in self.normalisers:
            print(normaliser)
            self.processes[normaliser['name']] = process_mapper.get(
>               normaliser['name'])(self.config[normaliser['name']]['config'])
E           KeyError: 'vt-notifications-feed'

main.py:26: KeyError
----------------------------- Captured stdout call -----------------------------
[*] Using processes mapper with dict_keys(['vt-notifications-feed']) keys
{'name': 'vt-notifications-feed', 'config': {'consumer': {'topic': 'some_topic', 'subscription': 'some_subscription'}}, 'publisher': {'topic': 'some_other_topic'}, 'project-id': 'some_id'}
=========================== short test summary info ============================
FAILED test.py::test_mapped_normaliser - KeyError: 'vt-notifications-feed'
========================= 1 failed, 2 passed in 0.33s ==========================

您甚至可以看到它打印密钥,并且所需的密钥就在那里。 所以我不确定 Python 在导致此问题的实现中所做的不同

您混淆了值和键。 有一个值为'vt-notifications-feed'的键值对,但它的键是'name'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM