0

I get KeyError when running following code:

r={'foo':'bar'} #no timestamp
def function(f=None):
    try:
        print(f) # giving r['timestamp'] KeyError
    except:
        print("problem")
function(f=r['timestamp'])

But this is working, it prints problem:

try:
    print(r['timestamp']) # giving r['timestamp'] KeyError
except:
    print("problem")

I can't understand why try-except block is not working in function.

Aprillion
  • 21,510
  • 5
  • 55
  • 89
bunyaminkirmizi
  • 540
  • 2
  • 6
  • 22

1 Answers1

2

function arguments are expressions that are evaluated before the value is passed to the function

so r['timestamp'] executes before function(f=...) an so before any try block captures any exceptions

you can use dict.get to avoid the KeyError:

function(f=r.get('timestamp', None))

or if you really need to capture the KeyError in the function:

def function(f=None):
    f = f or {}
    try:
        print(f['timestamp'])
    except KeyError:
        print("problem")
function(f=r)
Community
  • 1
  • 1
Aprillion
  • 21,510
  • 5
  • 55
  • 89