简体   繁体   English

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

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

I have a dict that maps strings to classes, so that they can be instantiated:我有一个将字符串映射到类的字典,以便可以实例化它们:

process_mapper = {VTNotifications.name: VTNotifications}

Where the class looks like: 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')

I've written a test that checks if the string does in fact return correctly, which passes:我编写了一个测试来检查字符串是否确实正确返回,它通过了:

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

However, when I attempt to pass pass the full config thats required to instantite the class, to a method does all the isntantiations, suddenly, it KeyErrors:但是,当我尝试将实例化 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 ==========================

You can even see it print the keys, and the required keys be there.您甚至可以看到它打印密钥,并且所需的密钥就在那里。 So I'm not sure what Python is doing differently across the implementations that is causing this issue所以我不确定 Python 在导致此问题的实现中所做的不同

You mixed up value and keys.您混淆了值和键。 There is a key-value pair with a value of 'vt-notifications-feed' , but its key is 'name'有一个值为'vt-notifications-feed'的键值对,但它的键是'name'

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

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