简体   繁体   中英

Recursive function return None

I have a function that runs over an API output and should return the path to specific key. Here is the function:

def find_path(obj, val, path=''):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k == val:
                return f'{path}[{k!r}]'
            return find_path(v, val, path + f'[{k!r}]')
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            if v == val:
                return f'{path}[{i!r}]'
            return find_path(v, val, path + f'[{i!r}]') 

API output Example:

ex = {'Resources': [{'uschemas': {'emailSelfUpdateAllowed': True,
                                  'emailVerificationDays': 30,
                                  'approvers': {'manager': False,
                                                'secondLevelManager': False,
                                                'owner': False,
                                                'workGroup': 'workgroup'}}}]}

When I run the function I get None :

bla = find_path(ex, 'approvers')
print(bla)
>>> None

I expect to get:

['Resources'][0]['uschemas']['approvers']

I can only get the expected output when I am using the function with print instead of return .

Can someone help me to understand why? and how can I make it work with returns and not prints because I need to use its output.

Thank you.

You need to return value after the for loop is done, this is the value returns from the recursion, if you don't have anything it will return None

def find_path(obj, val, path=''):
    p = []
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k == val:
                return f'{path}[{k!r}]'
            p = find_path(v, val, path + f'[{k!r}]')
        return p
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            if v == val:
                return f'{path}[{i!r}]'
            p = find_path(v, val, path + f'[{i!r}]')
        return p

bla = find_path(ex, 'approvers')
print(bla) # ['Resources'][0]['uschemas']['approvers']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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