Can I search for strings within a function in python?

I have a main python function that runs ~50 smaller functions that each put key-value pair(s) into a main dict. Sometimes these smaller functions fail (which is fine) but then they don’t put their key-value pair(s) into the main dict. This causes an issue when I need all the keys later, even the failed ones.

I’m wondering if it’s possible to do something like this:

mainDict = {}

def littleFunction1(a,b):
    z = a+b
    mainDict['z'] = z

def main(a,b):
        putKeysIntoMainDict(littleFunction1) # This function I cannot work out
    print(mainDict.keys()) # should print z

If the user runs main(2,4) that works, but if they run main(‘foo’,’bar’) then littleFunction1 will error and z isn’t entered into mainDict and the print will be blank.

Ideally putKeysIntoMainDict() searches through littleFunction1 to find mainDict[‘z’] = x and can return ‘z’.

Everything I’ve found searching for ‘search within a function’ has just returned the search function for strings.

If there are alternative ways of doing the same thing I’d be happy with that too.

edit: Changed code to be (hopefully) clearer. It’s an example, not my actual code because the littleFunctions I’m using are all 100s of lines long


You’re overcomplicating this. Simply set a default value with each function. If it fails, you will still have that value set:

def littleFunction1():
    mainDict['z'] = '-'
    x = 3
    y = 2
    z = x + y
    mainDict['z'] = z

Or even simpler, when accessing this mainDict, use .get. Any value that wasn’t set in one of the functions will return a default value:

>>> d = {'a': 5}
>>> d.get('a', '-')
>>> d.get('z', '-')