简体   繁体   中英

calling same function with different types in list

I have a list of dictionaries where I am traversing them on by one. eg.

def same_func(messages):
    for message in messages:
        #message is a dict here.

Now I also want to call this function in a different scenario where my messages is a list of tuples (dict and flag)

so suppose I have made this list like -

messages.append((message, flag))

and now I want to call the same function like same_func(messages) Then how can I make the same_func generic for both scenarios.

why not add a if statement in your for loop that determines the type and then handles the dict or tuple based of that.

ie:

def same_func(messages):
    for message in messages:
        if type(message) is dict:
            # handle dict
        elif type(message) is tuple:
            # handle tuple
        else: 
            # do something else

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