'Python suppress block for KeyError exception and code in block not working (assignment failing)

Tearing my hair out on this one and I'm sure its obvious to a pro... I've researched suppress, but nothing obvious I can find about why it won't enable my code.

I have a complex dict (based on imported json). I have a try:/except KeyError wrapper BUT within this large processing, I have suppress(KeyError) block for specific sections I want to ignore errors (note code below IS highly simplified).

When I reference a key that exists AFTER an exception would have been experienced in a previous line it doesn't populate the variable (code below)

If I reference the dict key out side of the block it works

I'm sure its something to do with the obj['a'] causes an issue to subsequent lines.

from contextlib import suppress

def func(obj):
    val=0
    try:
        with suppress(KeyError):
            dummy=obj['a']
            val=obj['x']     # this doesn't populate, unless I remove line above 
    except KeyError as ke:
        print('error')
        pass
    print (str(val))

if __name__ == '__main__':
    o={'x':99}
    func(o)   #hoping this prints 99


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source