简体   繁体   中英

How to pass whole statements as function parameters? python

I have this dict


dic = {'wow': 77, 'yy': 'gt', 'dwe': {'dwdw': {'fefe': 2006}}}


and I have this function


def get_missing_key(data, nest, default_value):
    try:
        return data + nest
    except KeyError as err:
        return default_value

and this is how I call it:


get_missing_key(dic, ['dwe']['dwdw']['fefe'], 16)

What I want is that I want the second parameter to get converted to normal python expression and do calculations with it

I want it to be like this



def get_missing_key(data, nest, default_value):
    try:
        return data['dwe']['dwdw']['fefe']
    except KeyError as err:
        return default_value

is there a way to achieve this?

But what I have clearly doesn't work, since I can't concatinate a dict with a list

You could use reduce like @kyle-parsons did, or you could manually loop:

lookup = ["dwe", "dwdw", "fefe"]

def find_missing(data, lookup, default):
    found = data
    for i in lookup:
        try:
            found = found[i]
        except KeyError:
            return default

    return found

You should pass your keys as a list.

from functools import reduce

def get_missing_key(data, nest, default_value):
    try:
        reduce(dict.__getitem__, nest, data)
    except KeyError:
        return default_value

In general, Python eagerly evaluates expressions and there's no way to delay that short of passing in strings of code to be built up and exec ed, but that's really not a good idea.

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